diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 9a56dca7f02..89e344b08d2 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -5,7 +5,7 @@ Also please indicate in the issue title which language/library is concerned. Eg: ##### Description - + ##### Swagger-codegen version @@ -37,7 +37,7 @@ Also please indicate in the issue title which language/library is concerned. Eg: ##### Related issues - + ##### Suggest a Fix diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000000..6f127186321 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,10 @@ +### PR checklist + +- [ ] Read the [contribution guildelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md). +- [ ] Ran the shell/batch 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) +- [ ] Filed the PR against the correct branch: master for non-breaking changes and `2.3.0` branch for breaking (non-backward compatible) changes. + +### Description of the PR + +(details of the change, additional tests that have been done, reference to the issue for tracking, etc) + diff --git a/.gitignore b/.gitignore index 589e45f6934..6f2eef3cee8 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ out/ *.iws classpath.txt version.properties +!modules/swagger-codegen-cli/src/main/resources/version.properties .project .classpath lib/* @@ -33,7 +34,7 @@ packages/ /target /generated-files -/nbactions.xml +nbactions.xml # scalatra samples/server-generator/scalatra/output @@ -56,6 +57,9 @@ samples/client/petstore/qt5cpp/PetStore/Makefile #Java/Android **/.gradle samples/client/petstore/java/hello.txt +samples/client/petstore/java/okhttp-gson/hello.txt +samples/client/petstore/java/jersey1/hello.txt +samples/client/petstore/java/jersey2-java8/hello.txt samples/client/petstore/android/default/hello.txt samples/client/petstore/android/volley/.gradle/ samples/client/petstore/android/volley/build/ @@ -121,6 +125,7 @@ samples/client/petstore/csharp/SwaggerClient/obj/Debug/ samples/client/petstore/csharp/SwaggerClient/bin/Debug/ samples/client/petstore/csharp/SwaggerClient/packages samples/client/petstore/csharp/SwaggerClient/TestResult.xml +samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.userprefs # Python *.pyc @@ -138,3 +143,6 @@ samples/client/petstore/typescript-angular/**/typings samples/client/petstore/typescript-fetch/**/dist/ samples/client/petstore/typescript-fetch/**/typings +# aspnet5 +samples/server/petstore/aspnet5/.vs/ + diff --git a/.travis.yml b/.travis.yml index 1a0be745a6e..1a62cea3161 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,16 +4,34 @@ jdk: - oraclejdk7 - oraclejdk8 +cache: + directories: + - $HOME/.m2 + services: - docker +addons: + hosts: + - petstore.swagger.io + before_install: # required when sudo: required for the Ruby petstore tests - gem install bundler - npm install -g typescript - 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 + # show host table to confirm petstore.swagger.io is mapped to localhost + - cat /etc/hosts 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" script: - mvn verify -Psamples diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a024ea98c41..32195b7df92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,14 +4,15 @@ - If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/swagger-api/swagger-codegen#getting-started) - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. - - File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information. + - File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information. + - Test with the latest master by building the JAR locally to see if the issue has already been addressed. - You can also make a suggestion or ask a question by opening an "issue". ## Before submitting a PR - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) to ensure no one else has reported something similar and no one is actively working on similar proposed change. - If no one has suggested something similar, open an ["issue"](https://github.com/swagger-api/swagger-codegen/issues) with your suggestion to gather feedback from the community. - - It's recommended to **create a new git branch** for the change + - It's recommended to **create a new git branch** for the change so that the merge commit message looks nicer in the commit history. ## How to contribute @@ -72,3 +73,4 @@ To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all t - Add test case(s) to cover the change - Document the fix in the code to make the code more readable - Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests) +- File a PR with meaningful title, description and commit messages. A good example is [PR-3306](https://github.com/swagger-api/swagger-codegen/pull/3306) diff --git a/README.md b/README.md index a549adec5b5..5ecc466d4c5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Swagger Code Generator -[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.svg)](https://travis-ci.org/swagger-api/swagger-codegen) +[![Build Status](https://img.shields.io/travis/swagger-api/swagger-codegen.svg?label=Petstore%20Integration%20Test)](https://travis-ci.org/swagger-api/swagger-codegen) +[![Run Status](https://img.shields.io/shippable/5782588a3be4f4faa56c5bea.svg?label=Mustache%20Template%20Test)](https://app.shippable.com/projects/5782588a3be4f4faa56c5bea) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/swagger-api/swagger-codegen?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/swagger-codegen-wh2wu) [![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) @@ -11,7 +13,7 @@ :warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning: ## Overview -This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. +This is the swagger codegen project, which allows generation of API client libraries, server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. @@ -58,8 +60,10 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.2.0-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.1.6 (**current stable**) | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) +2.3.0 (upcoming minor release) | TBD | 1.0, 1.1, 1.2, 2.0 | Minor release with breaking changes +2.2.2 (upcoming patch release) | TBD | 1.0, 1.1, 1.2, 2.0 | Patch release (without breaking changes) +2.2.1 (**current stable**) | 2016-08-07 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.1](https://github.com/swagger-api/swagger-codegen/tree/v2.2.1) +2.1.6 | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -68,7 +72,7 @@ Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes If you're looking for the latest stable version, you can grab it directly from maven central (you'll need java 7 runtime at a minimum): ``` -wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.1.6/swagger-codegen-cli-2.1.6.jar -O swagger-codegen-cli.jar +wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar -O swagger-codegen-cli.jar java -jar swagger-codegen-cli.jar help ``` @@ -97,7 +101,7 @@ export PATH=${JAVA_HOME}/bin:$PATH After cloning the project, you can build it from source with this command: ``` -mvn package +mvn clean package ``` ### Docker @@ -147,7 +151,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` (if you're on Windows, replace the last command with `java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l php -o c:\temp\php_api_client`) -You can also download the JAR (latest relesae) directly from [maven.org]( http://central.maven.org/maven2/io/swagger/swagger-codegen/2.1.6/swagger-codegen-2.1.6.jar) +You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar ) To get a list of **general** options available, please run `java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar help generate` @@ -375,7 +379,7 @@ To control the specific files being generated, you can pass a CSV list of what y -Dmodels=User -DsupportingFiles=StringUtil.java ``` -To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTest=false` and `-DapiDocs=false`. For models, `-DmodelTest=false` and `-DmodelDocs=false`. +To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTests=false` and `-DapiDocs=false`. For models, `-DmodelTests=false` and `-DmodelDocs=false`. These options default to true and don't limit the generation of the feature options listed above (like `-Dapi`): ``` @@ -495,8 +499,15 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/client/petstore/java \ -c path/to/config.json ``` -Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied -by passing them with `-D{optionName}={optionValue}**. +and `config.json` contains the following as an example: +``` +{ + "apiPackage" : "petstore" +} +``` + +Supported config options can be different per language. Running `config-help -l {lang}` will show available options. +**These options are applied via configuration file (e.g. config.json) or by passing them with `-D{optionName}={optionValue}**. (If `-D{optionName}` does not work, please open a [ticket](https://github.com/swagger-api/swagger-codegen/issues/new) and we'll look into it) ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l java @@ -738,18 +749,25 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Avenida Compras S.A.](https://www.avenida.com.ar) - [beemo](http://www.beemo.eu) - [bitly](https://bitly.com) +- [Bufferfly Network](https://www.butterflynetinc.com/) - [Cachet Financial](http://www.cachetfinancial.com/) - [CloudBoost](https://www.CloudBoost.io/) - [Conplement](http://www.conplement.de/) +- [Cummins] (http://www.cummins.com/) - [Cupix](http://www.cupix.com) -- [DBBest Technologies](https://www.dbbest.com) +- [DBBest Technologies](https://www.dbbest.com) +- [DecentFoX](http://decentfox.com/) - [DocuSign](https://www.docusign.com) - [Ergon](http://www.ergon.ch/) +- [EMC](https://www.emc.com/) - [eureka](http://eure.jp/) - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) - [Finder](http://en.finder.pl/) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) +- [Gear Zero Network](https://www.gearzero.ca) +- [Germin8](http://www.germin8.com) +- [goTransverse](http://www.gotransverse.com/api) - [GraphHopper](https://graphhopper.com/) - [Gravitate Solutions](http://gravitatesolutions.com/) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) @@ -760,20 +778,26 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Kabuku](http://www.kabuku.co.jp/en) - [Kuroi](http://kuroiwebdesign.com/) - [Kuary](https://kuary.com/) +- [Mindera](http://mindera.com/) - [Mporium](http://mporium.com/) - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) +- [Onedata](http://onedata.org) +- [OrderCloud.io](http://ordercloud.io) - [OSDN](https://osdn.jp) - [PagerDuty](https://www.pagerduty.com) - [Pepipost](https://www.pepipost.com) +- [Plexxi](http://www.plexxi.com) - [Pixoneye](http://www.pixoneye.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/) +- [QuantiModo](https://quantimo.do/) - [Rapid7](https://rapid7.com/) - [Reload! A/S](https://reload.dk/) - [REstore](https://www.restore.eu) - [Revault Sàrl](http://revault.ch) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [SCOOP Software GmbH](http://www.scoop-software.de) +- [Skurt](http://www.skurt.com) - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) @@ -787,7 +811,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you # Swagger Codegen Core Team -Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. +Swagger Codegen core team members are contributors who have been making significant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. ## API Clients | Languages | Core Team (join date) | @@ -800,6 +824,7 @@ Swaagger Codegen core team members are contributors who have been making signfic | Groovy | | | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | | Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) | +| Java (Spring Cloud) | @cbornet (2016/07/19) | | NodeJS/Javascript | @xhh (2016/05/01) | | ObjC | @mateuszmackowiak (2016/05/09) | | Perl | @wing328 (2016/05/01) | @@ -818,8 +843,8 @@ Swaagger Codegen core team members are contributors who have been making signfic | C# ASP.NET5 | @jimschubert (2016/05/01) | | Go Server | @guohuang (2016/06/13) | | Haskell Servant | | -| Java Spring Boot | | -| Java SpringMVC | @kolyjjj (2016/05/01) | +| Java Spring Boot | @cbornet (2016/07/19) | +| Java Spring MVC | @kolyjjj (2016/05/01) @cbornet (2016/07/19) | | Java JAX-RS | | | NancyFX | | | NodeJS | @kolyjjj (2016/05/01) | @@ -855,14 +880,20 @@ Here is a list of template creators: * Server Stubs * C# ASP.NET5: @jimschubert * C# NancyFX: @mstefaniuk + * Erlang Server: @galaxie * Go Server: @guohuang * Haskell Servant: @algas + * Java Undertow: @stevehu * Java Spring Boot: @diyfr * JAX-RS RestEasy: @chameleon82 - * JAX-RS CXF: @hiveship + * JAX-RS CXF: @hiveship + * JAX-RS CXF (CDI): @nickcmaynard * PHP Lumen: @abcsum * PHP Slim: @jfastnacht * Ruby on Rails 5: @zlx + * Documentation + * HTML Doc 2: @jhitchcock + * Confluence Wiki: @jhitchcock ## How to join the core team diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 00000000000..ab63a1ed443 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,42 @@ +# for CI with appveyor.yml +# Ref: http://www.yegor256.com/2015/01/10/windows-appveyor-maven.html +version: '{branch}-{build}' +os: Windows Server 2012 +hosts: + petstore.swagger.io: 127.0.0.1 +install: + - ps: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + if (!(Test-Path -Path "C:\maven" )) { + (new-object System.Net.WebClient).DownloadFile( + 'http://www.us.apache.org/dist/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.zip', + 'C:\maven-bin.zip' + ) + [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") + } + - cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;%JAVA_HOME%\bin;%PATH% + - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g + - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g + - cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5 + - git clone https://github.com/wing328/swagger-samples + - ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs" +build_script: + # build C# API client + - nuget restore samples\client\petstore\csharp\SwaggerClient\IO.Swagger.sln + - msbuild samples\client\petstore\csharp\SwaggerClient\IO.Swagger.sln /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" + # build C# API client (with PropertyChanged) + - nuget restore samples\client\petstore\csharp\SwaggerClientWithPropertyChanged\IO.Swagger.sln + - msbuild samples\client\petstore\csharp\SwaggerClientWithPropertyChanged\IO.Swagger.sln /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" + # install swagger codegen locally + - mvn clean install --batch-mode +test_script: + # test c# API client + - nunit-console samples\client\petstore\csharp\SwaggerClient\src\IO.Swagger.Test\bin\Debug\IO.Swagger.Test.dll --result=myresults.xml;format=AppVeyor + # test c# API client (with PropertyChanged) + - nunit-console samples\client\petstore\csharp\SwaggerClientWithPropertyChanged\src\IO.Swagger.Test\bin\Debug\IO.Swagger.Test.dll --result=myresults.xml;format=AppVeyor + + # generate all petstore clients + - .\bin\windows\run-all-petstore.cmd +cache: + - C:\maven\ + - C:\Users\appveyor\.m2 diff --git a/bin/akka-scala-petstore.sh b/bin/akka-scala-petstore.sh deleted file mode 100755 index 0fc8dafd2d7..00000000000 --- a/bin/akka-scala-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/akka-scala -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l akka-scala -o samples/client/petstore/akka-scala" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh deleted file mode 100755 index 849af6b5d4a..00000000000 --- a/bin/all-petstore.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/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 - -cd $APP_DIR -./bin/akka-scala-petstore.sh -./bin/android-petstore.sh -./bin/clojure-petstore.sh -./bin/csharp-petstore.sh -./bin/dynamic-html.sh -./bin/haskell-petstore.sh -./bin/html-petstore.sh -./bin/java-petstore.sh -./bin/java-petstore-jersey2.sh -./bin/java-petstore-okhttp-gson.sh -./bin/java-petstore-retrofit.sh -./bin/java-petstore-retrofit2.sh -./bin/jaxrs-petstore-server.sh -./bin/nodejs-petstore-server.sh -./bin/objc-petstore.sh -./bin/perl-petstore.sh -./bin/php-petstore.sh -./bin/python-petstore.sh -./bin/qt5-petstore.sh -./bin/ruby-petstore.sh -./bin/scala-async-petstore.sh -./bin/scala-petstore.sh -./bin/scalatra-petstore-server.sh -./bin/silex-petstore-server.sh -./bin/slim-petstore-server.sh -./bin/spring-mvc-petstore-server.sh -./bin/spring-mvc-petstore-j8-async-server.sh -./bin/swift-petstore.sh -./bin/tizen-petstore.sh -./bin/typescript-angular-petstore.sh -./bin/typescript-angular2-petstore.sh -./bin/typescript-angular2-petstore-with-npm.sh -./bin/typescript-node-petstore.sh -./bin/lumen-petstore-server.sh \ No newline at end of file diff --git a/bin/android-petstore-httpclient.sh b/bin/android-petstore-httpclient.sh deleted file mode 100755 index 097484e0410..00000000000 --- a/bin/android-petstore-httpclient.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -Dlibrary=httpclient -o samples/client/petstore/android/httpclient" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-petstore-volley.json b/bin/android-petstore-volley.json deleted file mode 100644 index 913ef5c0139..00000000000 --- a/bin/android-petstore-volley.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "volley", - "artifactId": "swagger-petstore-android-volley" -} diff --git a/bin/android-petstore-volley.sh b/bin/android-petstore-volley.sh deleted file mode 100755 index 6bd15b7f571..00000000000 --- a/bin/android-petstore-volley.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l android -c bin/android-petstore-volley.json -o samples/client/petstore/android/volley" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-petstore.sh b/bin/android-petstore.sh deleted file mode 100755 index 67256debeb0..00000000000 --- a/bin/android-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l android -o samples/client/petstore/android/volley" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/aspnet5-petstore-server.sh b/bin/aspnet5-petstore-server.sh deleted file mode 100755 index 4481b4b318f..00000000000 --- a/bin/aspnet5-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env 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 - -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 -l aspnet5 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -o samples/server/petstore/aspnet5" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/clojure-petstore.sh b/bin/clojure-petstore.sh deleted file mode 100755 index 1f53d9d386c..00000000000 --- a/bin/clojure-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l clojure -o samples/client/petstore/clojure" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/cpprest-petstore.sh b/bin/cpprest-petstore.sh deleted file mode 100755 index 93f7ad609cc..00000000000 --- a/bin/cpprest-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/cpprest -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l cpprest -o samples/client/petstore/cpprest" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/csharp-dotnet2-petstore.sh b/bin/csharp-dotnet2-petstore.sh deleted file mode 100755 index a63bfa35bfd..00000000000 --- a/bin/csharp-dotnet2-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l CsharpDotNet2 -o samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh deleted file mode 100755 index a82efa9af10..00000000000 --- a/bin/csharp-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/SwaggerClient" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/dart-petstore.sh b/bin/dart-petstore.sh deleted file mode 100755 index 292af62977f..00000000000 --- a/bin/dart-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/dynamic-html.sh b/bin/dynamic-html.sh deleted file mode 100755 index 826b70cec78..00000000000 --- a/bin/dynamic-html.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dynamic-html -o samples/dynamic-html" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/flash-petstore.sh b/bin/flash-petstore.sh deleted file mode 100755 index 804b90249c2..00000000000 --- a/bin/flash-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/flash -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l flash -o samples/client/petstore/flash" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/flaskConnexion.sh b/bin/flaskConnexion.sh deleted file mode 100755 index 563718f9061..00000000000 --- a/bin/flaskConnexion.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion " - -java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/go-petstore-server.sh b/bin/go-petstore-server.sh deleted file mode 100755 index a668a1cfbdd..00000000000 --- a/bin/go-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver " - -java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/go-petstore.sh b/bin/go-petstore.sh deleted file mode 100755 index eea1aaaf6f3..00000000000 --- a/bin/go-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/go -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go -o samples/client/petstore/go/go-petstore -DpackageName=petstore " - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/groovy-petstore.sh b/bin/groovy-petstore.sh deleted file mode 100755 index 6afb14a7f09..00000000000 --- a/bin/groovy-petstore.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l groovy -o samples/client/petstore/groovy -DhideGenerationTimestamp=true" -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/haskell-servant-petstore.sh b/bin/haskell-servant-petstore.sh deleted file mode 100755 index 0095e2ccc7c..00000000000 --- a/bin/haskell-servant-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/haskell-servant -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l haskell -o samples/server/petstore/haskell-servant" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/html-petstore.sh b/bin/html-petstore.sh deleted file mode 100755 index 030c36d03e1..00000000000 --- a/bin/html-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l html -o samples/html" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-inflector-petstore-server.sh b/bin/java-inflector-petstore-server.sh deleted file mode 100755 index 2fe4c8cac0b..00000000000 --- a/bin/java-inflector-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/JavaInflector -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l inflector -o samples/server/petstore/java-inflector" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh deleted file mode 100755 index 143ebc819c5..00000000000 --- a/bin/java-petstore-all.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -# update java petstore for all supported http libraries - -./bin/java-petstore.sh -./bin/java-petstore-jersey2.sh -./bin/java-petstore-feign.sh -./bin/java-petstore-okhttp-gson.sh -./bin/java-petstore-retrofit.sh -./bin/java-petstore-retrofit2.sh -./bin/java-petstore-retrofit2rx.sh diff --git a/bin/java-petstore-feign.json b/bin/java-petstore-feign.json deleted file mode 100644 index 5502ee3bbad..00000000000 --- a/bin/java-petstore-feign.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "feign", - "artifactId": "swagger-petstore-feign" -} diff --git a/bin/java-petstore-feign.sh b/bin/java-petstore-feign.sh deleted file mode 100755 index 160dbb46b1b..00000000000 --- a/bin/java-petstore-feign.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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/feign -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/client/petstore/java/feign/src/main" -rm -rf samples/client/petstore/java/feign/src/main -find samples/client/petstore/java/feign -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-jersey2.json b/bin/java-petstore-jersey2.json deleted file mode 100644 index af343e1d6b8..00000000000 --- a/bin/java-petstore-jersey2.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "jersey2", - "artifactId": "swagger-petstore-jersey2" -} \ No newline at end of file diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh deleted file mode 100755 index 0850bdbb4f4..00000000000 --- a/bin/java-petstore-jersey2.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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 java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2 -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/client/petstore/java/jersey2/src/main" -rm -rf samples/client/petstore/java/jersey2/src/main -find samples/client/petstore/java/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-okhttp-gson.json b/bin/java-petstore-okhttp-gson.json deleted file mode 100644 index b894d172630..00000000000 --- a/bin/java-petstore-okhttp-gson.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "okhttp-gson", - "artifactId": "swagger-petstore-okhttp-gson" -} diff --git a/bin/java-petstore-okhttp-gson.sh b/bin/java-petstore-okhttp-gson.sh deleted file mode 100755 index ef57de98775..00000000000 --- a/bin/java-petstore-okhttp-gson.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/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/okhttp-gson -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DhideGenerationTimestamp=true" - -rm -rf samples/client/petstore/java/okhttp-gson/src/main -find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit.json b/bin/java-petstore-retrofit.json deleted file mode 100644 index 86da9d17099..00000000000 --- a/bin/java-petstore-retrofit.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "retrofit", - "artifactId": "swagger-petstore-retrofit" -} diff --git a/bin/java-petstore-retrofit.sh b/bin/java-petstore-retrofit.sh deleted file mode 100755 index 3b370fde7dd..00000000000 --- a/bin/java-petstore-retrofit.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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 java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/client/petstore/java/retrofit/src/main" -rm -rf samples/client/petstore/java/retrofit/src/main -find samples/client/petstore/java/retrofit -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2.json b/bin/java-petstore-retrofit2.json deleted file mode 100644 index 4829fd6dd4b..00000000000 --- a/bin/java-petstore-retrofit2.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "retrofit2", - "artifactId": "swagger-petstore-retrofit2" -} diff --git a/bin/java-petstore-retrofit2.sh b/bin/java-petstore-retrofit2.sh deleted file mode 100755 index 30cb805c3ec..00000000000 --- a/bin/java-petstore-retrofit2.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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/retrofit2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2 -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/client/petstore/java/retrofit2/src/main" -rm -rf samples/client/petstore/java/retrofit2/src/main -find samples/client/petstore/java/retrofit2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2rx.json b/bin/java-petstore-retrofit2rx.json deleted file mode 100644 index c9e4301f2da..00000000000 --- a/bin/java-petstore-retrofit2rx.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "library": "retrofit2", - "artifactId": "swagger-petstore-retrofit2-rx" -} diff --git a/bin/java-petstore-retrofit2rx.sh b/bin/java-petstore-retrofit2rx.sh deleted file mode 100755 index 4b9c6512b10..00000000000 --- a/bin/java-petstore-retrofit2rx.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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/retrofit2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true,hideGenerationTimestamp=true" - -echo "Removing files and folders under samples/client/petstore/java/retrofit2rx/src/main" -rm -rf samples/client/petstore/java/retrofit2rx/src/main -find samples/client/petstore/java/retrofit2rx -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh deleted file mode 100755 index be6472d7aad..00000000000 --- a/bin/java-petstore.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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 java -o samples/client/petstore/java/default -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/client/petstore/java/default/src/main" -rm -rf samples/client/petstore/java/default/src/main -find samples/client/petstore/java/default -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/javascript-closure-angular.sh b/bin/javascript-closure-angular.sh deleted file mode 100755 index 9ef43666f88..00000000000 --- a/bin/javascript-closure-angular.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l javascript-closure-angular -o samples/client/petstore/javascript-closure-angular" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/javascript-petstore.sh b/bin/javascript-petstore.sh deleted file mode 100755 index 2eb26210e0a..00000000000 --- a/bin/javascript-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/Javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l javascript -o samples/client/petstore/javascript" - -java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/javascript-promise-petstore.sh b/bin/javascript-promise-petstore.sh deleted file mode 100755 index fac0f221424..00000000000 --- a/bin/javascript-promise-petstore.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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/Javascript \ --i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l javascript \ --o samples/client/petstore/javascript-promise \ ---additional-properties usePromises=true" - -java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-petstore-server.sh b/bin/jaxrs-cxf-petstore-server.sh deleted file mode 100755 index bac9cb1d4eb..00000000000 --- a/bin/jaxrs-cxf-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf -DhideGenerationTimestamp=true" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-jersey1-petstore-server.sh b/bin/jaxrs-jersey1-petstore-server.sh deleted file mode 100755 index 914900a1e7e..00000000000 --- a/bin/jaxrs-jersey1-petstore-server.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server" - -echo "Removing files and folders under samples/server/petstore/jaxrs/jersey1/src/main" -rm -rf samples/server/petstore/jaxrs/jersey1/src/main -find samples/server/petstore/jaxrs/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh deleted file mode 100755 index e32251ed149..00000000000 --- a/bin/jaxrs-petstore-server.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey2 -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/server/petstore/jaxrs/jersey2/src/main" -rm -rf samples/server/petstore/jaxrs/jersey2/src/main -find samples/server/petstore/jaxrs/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-resteasy-joda-petstore-server.json b/bin/jaxrs-resteasy-joda-petstore-server.json deleted file mode 100755 index 785c7acdc6a..00000000000 --- a/bin/jaxrs-resteasy-joda-petstore-server.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "dateLibrary": "joda" -} diff --git a/bin/jaxrs-resteasy-joda-petstore-server.sh b/bin/jaxrs-resteasy-joda-petstore-server.sh deleted file mode 100755 index c1bbf6d71bf..00000000000 --- a/bin/jaxrs-resteasy-joda-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-resteasy -o samples/server/petstore/jaxrs-resteasy/joda -DhideGenerationTimestamp=true -c ./bin/jaxrs-resteasy-joda-petstore-server.json" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-resteasy-petstore-server.sh b/bin/jaxrs-resteasy-petstore-server.sh deleted file mode 100755 index 8fb30411d64..00000000000 --- a/bin/jaxrs-resteasy-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-resteasy -o samples/server/petstore/jaxrs-resteasy/default -DhideGenerationTimestamp=true" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-spec-petstore-server.sh b/bin/jaxrs-spec-petstore-server.sh deleted file mode 100644 index 768d20d4748..00000000000 --- a/bin/jaxrs-spec-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-spec -o samples/server/petstore/jaxrs-spec -DhideGenerationTimestamp=true" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/lumen-petstore-server.sh b/bin/lumen-petstore-server.sh deleted file mode 100755 index a4a5df0f817..00000000000 --- a/bin/lumen-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l lumen -o samples/server/petstore/lumen" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nodejs-petstore-server.sh b/bin/nodejs-petstore-server.sh deleted file mode 100755 index 3fff1bdc0c0..00000000000 --- a/bin/nodejs-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server -o samples/server/petstore/nodejs" - -java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/objc-petstore-coredata.sh b/bin/objc-petstore-coredata.sh deleted file mode 100755 index 8487adfc42b..00000000000 --- a/bin/objc-petstore-coredata.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/objc -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -DapiDocs=false,modelDocs=false -o samples/client/petstore/objc/core-data --additional-properties coreData=true" - -java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh deleted file mode 100755 index 71480ff1595..00000000000 --- a/bin/objc-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/objc -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc/default" - -java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/perl-petstore.sh b/bin/perl-petstore.sh deleted file mode 100755 index f3eb5b17bd9..00000000000 --- a/bin/perl-petstore.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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" -# complex module name used for testing -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l perl -o samples/client/petstore/perl" - -java $JAVA_OPTS -jar $executable $ags - -java $JAVA_OPTS -jar $executable $ags --additional-properties moduleName=Something::Deep -o samples/client/petstore/perl/deep_module_test diff --git a/bin/php-petstore.sh b/bin/php-petstore.sh deleted file mode 100755 index 3b25c1c1cc3..00000000000 --- a/bin/php-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/php -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l php -o samples/client/petstore/php" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh deleted file mode 100755 index 0fe89ea39ed..00000000000 --- a/bin/python-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l python -o samples/client/petstore/python -DpackageName=petstore_api" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/qt5-petstore.sh b/bin/qt5-petstore.sh deleted file mode 100755 index 40f05211cd0..00000000000 --- a/bin/qt5-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/qt5cpp -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l qt5cpp -o samples/client/petstore/qt5cpp" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/rails5-petstore-server.sh b/bin/rails5-petstore-server.sh deleted file mode 100755 index 28b3ca3069b..00000000000 --- a/bin/rails5-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/rails5 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l rails5 -o samples/server/petstore/rails5" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/ruby-petstore.json b/bin/ruby-petstore.json deleted file mode 100644 index ddb753471a1..00000000000 --- a/bin/ruby-petstore.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "gemName": "petstore", - "moduleName": "Petstore", - "gemVersion": "1.0.0" -} diff --git a/bin/ruby-petstore.sh b/bin/ruby-petstore.sh deleted file mode 100755 index f1c87e32028..00000000000 --- a/bin/ruby-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/ruby -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l ruby -c bin/ruby-petstore.json -o samples/client/petstore/ruby" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-async-petstore.sh b/bin/scala-async-petstore.sh deleted file mode 100755 index 5456c98b27a..00000000000 --- a/bin/scala-async-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/asyncscala -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l async-scala -o samples/client/petstore/async-scala" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-petstore.sh b/bin/scala-petstore.sh deleted file mode 100755 index b0ea4108160..00000000000 --- a/bin/scala-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/scala -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l scala -o samples/client/petstore/scala" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scalatra-petstore-server.sh b/bin/scalatra-petstore-server.sh deleted file mode 100755 index c902aec03bb..00000000000 --- a/bin/scalatra-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/scalatra -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l scalatra -o samples/server/petstore/scalatra" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/csharp-petstore.sh b/bin/security/csharp-petstore.sh deleted file mode 100755 index 375e33fac40..00000000000 --- a/bin/security/csharp-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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-security-test.yaml -l csharp -o samples/client/petstore-security-test/csharp/SwaggerClient" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/java-petstore-okhttp-gson.sh b/bin/security/java-petstore-okhttp-gson.sh deleted file mode 100755 index 0fd421fc880..00000000000 --- a/bin/security/java-petstore-okhttp-gson.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/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/okhttp-gson -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore-security-test/java/okhttp-gson -DhideGenerationTimestamp=true" - -rm -rf samples/client/petstore-security-test/java/okhttp-gson/src/main -find samples/client/petstore-security-test/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/javascript-closure-angular.sh b/bin/security/javascript-closure-angular.sh deleted file mode 100755 index 4f5dd18c62f..00000000000 --- a/bin/security/javascript-closure-angular.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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-security-test.yaml -l javascript-closure-angular -o samples/client/petstore-security-test/javascript-closure-angular" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/javascript-petstore.sh b/bin/security/javascript-petstore.sh deleted file mode 100755 index 7b1443afce4..00000000000 --- a/bin/security/javascript-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/Javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l javascript -o samples/client/petstore-security-test/javascript" - -java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/lumen-petstore-server.sh b/bin/security/lumen-petstore-server.sh deleted file mode 100755 index 96dddcf4786..00000000000 --- a/bin/security/lumen-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l lumen -o samples/server/petstore-security-test/lumen" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/perl-petstore.sh b/bin/security/perl-petstore.sh deleted file mode 100755 index ebc92367a22..00000000000 --- a/bin/security/perl-petstore.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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" -# complex module name used for testing -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l perl -o samples/client/petstore-security-test/perl" - -java $JAVA_OPTS -jar $executable $ags - -java $JAVA_OPTS -jar $executable $ags --additional-properties moduleName=Something::Deep -o samples/client/petstore-security-test/perl/deep_module_test diff --git a/bin/security/php-petstore.sh b/bin/security/php-petstore.sh deleted file mode 100755 index 51b61127dd2..00000000000 --- a/bin/security/php-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/php -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l php -o samples/client/petstore-security-test/php" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/python-petstore.sh b/bin/security/python-petstore.sh deleted file mode 100755 index 11c8f573fda..00000000000 --- a/bin/security/python-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l python -o samples/client/petstore-security-test/python -DpackageName=petstore_api" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/ruby-petstore.sh b/bin/security/ruby-petstore.sh deleted file mode 100755 index 14bf4972eff..00000000000 --- a/bin/security/ruby-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/ruby -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l ruby -c bin/ruby-petstore.json -o samples/client/petstore-security-test/ruby" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/silex-petstore-server.sh b/bin/security/silex-petstore-server.sh deleted file mode 100755 index a939c2da9a8..00000000000 --- a/bin/security/silex-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l silex-PHP -o samples/server/petstore-security-test/silex" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/slim-petstore-server.sh b/bin/security/slim-petstore-server.sh deleted file mode 100755 index a52c8bb3b9a..00000000000 --- a/bin/security/slim-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/slim -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l slim -o samples/server/petstore-security-test/slim" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/silex-petstore-server.sh b/bin/silex-petstore-server.sh deleted file mode 100755 index c273102828b..00000000000 --- a/bin/silex-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l silex-PHP -o samples/server/petstore/silex" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/sinatra-petstore-server.sh b/bin/sinatra-petstore-server.sh deleted file mode 100755 index 7c99e9a068a..00000000000 --- a/bin/sinatra-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/sinatra -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l sinatra -o samples/server/petstore/sinatra" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/slim-petstore-server.sh b/bin/slim-petstore-server.sh deleted file mode 100755 index 6e2e5270542..00000000000 --- a/bin/slim-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/slim -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l slim -o samples/server/petstore/slim" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-mvc-petstore-j8-async-server.sh b/bin/spring-mvc-petstore-j8-async-server.sh deleted file mode 100755 index 3d0681f7ee8..00000000000 --- a/bin/spring-mvc-petstore-j8-async-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring --library spring-mvc -o samples/server/petstore/spring-mvc-j8-async -c bin/spring-mvc-petstore-j8-async.json -DhideGenerationTimestamp=true,java8=true,async=true" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-mvc-petstore-j8-async.json b/bin/spring-mvc-petstore-j8-async.json deleted file mode 100644 index c19430ec9ab..00000000000 --- a/bin/spring-mvc-petstore-j8-async.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "library": "j8-async" -} diff --git a/bin/spring-mvc-petstore-server.sh b/bin/spring-mvc-petstore-server.sh deleted file mode 100755 index 736688491c5..00000000000 --- a/bin/spring-mvc-petstore-server.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring --library spring-mvc -o samples/server/petstore/spring-mvc -DhideGenerationTimestamp=true" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-stubs.sh b/bin/spring-stubs.sh deleted file mode 100755 index 3d748a5b6f5..00000000000 --- a/bin/spring-stubs.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/client/petstore/spring-stubs -DinterfaceOnly=true,singleContentTypes=true,hideGenerationTimestamp=true" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/springboot-petstore-server.sh b/bin/springboot-petstore-server.sh deleted file mode 100755 index 565e35d53d9..00000000000 --- a/bin/springboot-petstore-server.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/server/petstore/springboot -DhideGenerationTimestamp=true" - -echo "Removing files and folders under samples/server/petstore/springboot/src/main" -rm -rf samples/server/petstore/springboot/src/main -find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-all.sh b/bin/swift-petstore-all.sh deleted file mode 100755 index e74eba37704..00000000000 --- a/bin/swift-petstore-all.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default" - -echo "#### Petstore Swift API client (default) ####" -java $JAVA_OPTS -jar $executable $ags - -ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" -echo "#### Petstore Swift API client (promisekit) ####" -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-promisekit.json b/bin/swift-petstore-promisekit.json deleted file mode 100644 index 1211352cc55..00000000000 --- a/bin/swift-petstore-promisekit.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "podSummary": "PetstoreClient", - "podHomepage": "https://github.com/swagger-api/swagger-codegen", - "podAuthors": "", - "projectName": "PetstoreClient", - "responseAs": "PromiseKit" -} \ No newline at end of file diff --git a/bin/swift-petstore-promisekit.sh b/bin/swift-petstore-promisekit.sh deleted file mode 100755 index d2787a876a0..00000000000 --- a/bin/swift-petstore-promisekit.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore.json b/bin/swift-petstore.json deleted file mode 100644 index 3d9ecfd5d0a..00000000000 --- a/bin/swift-petstore.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "podSummary": "PetstoreClient", - "podHomepage": "https://github.com/swagger-api/swagger-codegen", - "podAuthors": "", - "projectName": "PetstoreClient" -} \ No newline at end of file diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh deleted file mode 100755 index 3747b3adca4..00000000000 --- a/bin/swift-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/tizen-petstore.sh b/bin/tizen-petstore.sh deleted file mode 100755 index 01a26b885d1..00000000000 --- a/bin/tizen-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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/tizen -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l tizen -o samples/client/petstore/tizen" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular-petstore.sh b/bin/typescript-angular-petstore.sh deleted file mode 100755 index 60c10790c90..00000000000 --- a/bin/typescript-angular-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-angular -o samples/client/petstore/typescript-angular" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular2-petstore-all.sh b/bin/typescript-angular2-petstore-all.sh deleted file mode 100755 index b3fc0df2126..00000000000 --- a/bin/typescript-angular2-petstore-all.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/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" - -echo "Typescript Petstore API client (default)" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -o samples/client/petstore/typescript-angular2/default" -java $JAVA_OPTS -jar $executable $ags - -echo "Typescript Petstore API client (npm setting)" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm" -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular2-petstore-with-npm.sh b/bin/typescript-angular2-petstore-with-npm.sh deleted file mode 100755 index 305a3e0b39d..00000000000 --- a/bin/typescript-angular2-petstore-with-npm.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-angular2 -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular2-petstore.sh b/bin/typescript-angular2-petstore.sh deleted file mode 100755 index f26dd0f668f..00000000000 --- a/bin/typescript-angular2-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-angular2 -o samples/client/petstore/typescript-angular2/default" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-all.sh b/bin/typescript-fetch-petstore-all.sh deleted file mode 100755 index 6365b9032a6..00000000000 --- a/bin/typescript-fetch-petstore-all.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -./bin/typescript-fetch-petstore-target-es6.sh -./bin/typescript-fetch-petstore-with-npm-version.sh -./bin/typescript-fetch-petstore.sh diff --git a/bin/typescript-fetch-petstore-target-es6.json b/bin/typescript-fetch-petstore-target-es6.json deleted file mode 100644 index 83914bd569c..00000000000 --- a/bin/typescript-fetch-petstore-target-es6.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "supportsES6": true -} diff --git a/bin/typescript-fetch-petstore-target-es6.sh b/bin/typescript-fetch-petstore-target-es6.sh deleted file mode 100755 index 84a6562eeb6..00000000000 --- a/bin/typescript-fetch-petstore-target-es6.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-with-npm-version.json b/bin/typescript-fetch-petstore-with-npm-version.json deleted file mode 100644 index b8193c8fa74..00000000000 --- a/bin/typescript-fetch-petstore-with-npm-version.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "npmName": "@swagger/typescript-fetch-petstore", - "npmVersion": "0.0.1" -} diff --git a/bin/typescript-fetch-petstore-with-npm-version.sh b/bin/typescript-fetch-petstore-with-npm-version.sh deleted file mode 100755 index fd9225f0e72..00000000000 --- a/bin/typescript-fetch-petstore-with-npm-version.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore.sh b/bin/typescript-fetch-petstore.sh deleted file mode 100755 index 50d56f34609..00000000000 --- a/bin/typescript-fetch-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-node-petstore-all.sh b/bin/typescript-node-petstore-all.sh deleted file mode 100755 index 65f25060725..00000000000 --- a/bin/typescript-node-petstore-all.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/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" - -echo "Typescript node Petstore API client (default setting)" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -o samples/client/petstore/typescript-node/default" -java $JAVA_OPTS -jar $executable $ags - -echo "Typescript node Petstore API client with npm setting" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-node/npm" -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-node-petstore-with-npm.sh b/bin/typescript-node-petstore-with-npm.sh deleted file mode 100755 index e369be758e7..00000000000 --- a/bin/typescript-node-petstore-with-npm.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-node -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-node/npm" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-node-petstore.sh b/bin/typescript-node-petstore.sh deleted file mode 100755 index c9d16d96113..00000000000 --- a/bin/typescript-node-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/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.json -l typescript-node -o samples/client/petstore/typescript-node/default" - -java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-petstore-npm.json b/bin/typescript-petstore-npm.json deleted file mode 100755 index 1eb3264f596..00000000000 --- a/bin/typescript-petstore-npm.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "npmName": "@swagger/angular2-typescript-petstore", - "npmVersion": "0.0.1", - "npmRepository" : "https://skimdb.npmjs.com/registry", - "snapshot" : true -} diff --git a/bin/windows/akka-scala-petstore.bat b/bin/windows/akka-scala-petstore.bat deleted file mode 100755 index ecd7433d2e2..00000000000 --- a/bin/windows/akka-scala-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\akka-scala -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l akka-scala -o samples\client\petstore\akka-scala - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/android-petstore.bat b/bin/windows/android-petstore.bat deleted file mode 100755 index 03ee8a85836..00000000000 --- a/bin/windows/android-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\android -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l android -o samples\client\petstore\android\default - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/aspnet5-petstore-server.bat b/bin/windows/aspnet5-petstore-server.bat deleted file mode 100755 index 955ad6677b8..00000000000 --- a/bin/windows/aspnet5-petstore-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\aspnet5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l aspnet5 -o samples\server\petstore\aspnet5\ - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/async-scala-petstore.bat b/bin/windows/async-scala-petstore.bat deleted file mode 100755 index d2b772b91b8..00000000000 --- a/bin/windows/async-scala-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\asyncscala -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l async-scala -o samples\client\petstore\async-scala - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/clojure-petstore.bat b/bin/windows/clojure-petstore.bat deleted file mode 100755 index bfbb6663d11..00000000000 --- a/bin/windows/clojure-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\clojure -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l clojure -o samples\client\petstore\clojure - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/cpprest-petstore.bat b/bin/windows/cpprest-petstore.bat deleted file mode 100755 index 43312669840..00000000000 --- a/bin/windows/cpprest-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\cpprest -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l cpprest -o samples\client\petstore\cpprest - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-petstore.bat b/bin/windows/csharp-petstore.bat deleted file mode 100755 index fbfc18d334d..00000000000 --- a/bin/windows/csharp-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\csharp -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l csharp -o samples\client\petstore\csharp\SwaggerClient - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/dart-petstore.bat b/bin/windows/dart-petstore.bat deleted file mode 100755 index bbf77fed2cc..00000000000 --- a/bin/windows/dart-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\dart -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l dart -o samples\client\petstore\dart - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/dynamic-html-petstore.bat b/bin/windows/dynamic-html-petstore.bat deleted file mode 100755 index 27595a54a16..00000000000 --- a/bin/windows/dynamic-html-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\dynamic-html -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l dynamic-html -o samples\client\petstore\dynamic-html - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/flash-petstore.bat b/bin/windows/flash-petstore.bat deleted file mode 100755 index 9e4445b77ea..00000000000 --- a/bin/windows/flash-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\flash -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l flash -o samples\client\petstore\flash - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/go-petstore.bat b/bin/windows/go-petstore.bat deleted file mode 100755 index 050bfd23cc8..00000000000 --- a/bin/windows/go-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\go -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l go -o samples\client\petstore\go - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/html-petstore.bat b/bin/windows/html-petstore.bat deleted file mode 100755 index 82cc490027a..00000000000 --- a/bin/windows/html-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\html -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l html -o samples\client\petstore\html - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/java-petstore-okhttp-gson.bat b/bin/windows/java-petstore-okhttp-gson.bat deleted file mode 100755 index e7c1dde982a..00000000000 --- a/bin/windows/java-petstore-okhttp-gson.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/java-petstore.bat b/bin/windows/java-petstore.bat deleted file mode 100755 index 02a81e1adbf..00000000000 --- a/bin/windows/java-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java -DdateLibrary=joda,hideGenerationTimestamp=true - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/javascript-petstore.bat b/bin/windows/javascript-petstore.bat deleted file mode 100755 index 6ee220a7062..00000000000 --- a/bin/windows/javascript-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\javascript -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l javascript -o samples\client\petstore\javascript - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/nancyfx-petstore-server.bat b/bin/windows/nancyfx-petstore-server.bat deleted file mode 100644 index 72af10287ce..00000000000 --- a/bin/windows/nancyfx-petstore-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\nancyfx -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l nancyfx -o samples\server\petstore\nancyfx\ - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/objc-petstore.bat b/bin/windows/objc-petstore.bat deleted file mode 100755 index 9e64a80ac00..00000000000 --- a/bin/windows/objc-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\objc -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l objc -o samples\client\petstore\objc\default - -java %JAVA_OPTS% -DappName=PetstoreClient -jar %executable% %ags% diff --git a/bin/windows/perl-petstore.bat b/bin/windows/perl-petstore.bat deleted file mode 100755 index da526e40dd7..00000000000 --- a/bin/windows/perl-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\perl -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l perl -o samples\client\petstore\perl - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/php-petstore.bat b/bin/windows/php-petstore.bat deleted file mode 100755 index cc10b72a609..00000000000 --- a/bin/windows/php-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\php -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l php -o samples\client\petstore\php - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/python-petstore.bat b/bin/windows/python-petstore.bat deleted file mode 100755 index 2762cf15b81..00000000000 --- a/bin/windows/python-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\python -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l python -o samples\client\petstore\python - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/qt5cpp-petstore.bat b/bin/windows/qt5cpp-petstore.bat deleted file mode 100755 index 3c5b849a3f1..00000000000 --- a/bin/windows/qt5cpp-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\qt5cpp -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l qt5cpp -o samples\client\petstore\qt5cpp - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/rails-petstore-server.bat b/bin/windows/rails-petstore-server.bat deleted file mode 100644 index 55677b55197..00000000000 --- a/bin/windows/rails-petstore-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l aspnet5 -o samples\server\petstore\rails5\ - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/rails5-petstore-server.bat b/bin/windows/rails5-petstore-server.bat deleted file mode 100755 index a0316279784..00000000000 --- a/bin/windows/rails5-petstore-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l rails5 -o samples\server\petstore\rails5\ - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/ruby-petstore.bat b/bin/windows/ruby-petstore.bat deleted file mode 100755 index 3642a6e19ba..00000000000 --- a/bin/windows/ruby-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\ruby -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l ruby -o samples\client\petstore\ruby - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/scala-petstore.bat b/bin/windows/scala-petstore.bat deleted file mode 100755 index 5d72d6e0c61..00000000000 --- a/bin/windows/scala-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\scala -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l scala -o samples\client\petstore\scala - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/spring-mvc-petstore-j8-async-server.bat b/bin/windows/spring-mvc-petstore-j8-async-server.bat deleted file mode 100644 index 601de1ff6f8..00000000000 --- a/bin/windows/spring-mvc-petstore-j8-async-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringMVC -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l spring-mvc -o samples/server/petstore/spring-mvc-j8-async -c bin/spring-mvc-petstore-j8-async.json - -java %JAVA_OPTS% -jar %executable% %ags% \ No newline at end of file diff --git a/bin/windows/spring-mvc-petstore-server.bat b/bin/windows/spring-mvc-petstore-server.bat deleted file mode 100644 index f4ab64d5bd8..00000000000 --- a/bin/windows/spring-mvc-petstore-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringMVC -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l spring-mvc -o samples\server\petstore\spring-mvc - -java %JAVA_OPTS% -jar %executable% %ags% \ No newline at end of file diff --git a/bin/windows/springboot-petstore-server.bat b/bin/windows/springboot-petstore-server.bat deleted file mode 100644 index 18077852db3..00000000000 --- a/bin/windows/springboot-petstore-server.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringBoot -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l springboot -o samples\server\petstore\springboot - -java %JAVA_OPTS% -jar %executable% %ags% \ No newline at end of file diff --git a/bin/windows/swift-petstore.bat b/bin/windows/swift-petstore.bat deleted file mode 100755 index 31d19c18399..00000000000 --- a/bin/windows/swift-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\swift -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l swift -o samples\client\petstore\swift - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/tizen-petstore.bat b/bin/windows/tizen-petstore.bat deleted file mode 100755 index 27122c2cb94..00000000000 --- a/bin/windows/tizen-petstore.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\tizen -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l tizen -o samples\client\petstore\tizen - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-angular.bat b/bin/windows/typescript-angular.bat deleted file mode 100755 index d77012e1b3d..00000000000 --- a/bin/windows/typescript-angular.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-angular -o samples\client\petstore\typescript-angular - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-angular2-with-npm.bat b/bin/windows/typescript-angular2-with-npm.bat deleted file mode 100644 index dcbd6df8155..00000000000 --- a/bin/windows/typescript-angular2-with-npm.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -c bin/typescript-petstore-npm.json -l typescript-angular2 -o samples\client\petstore\typescript-angular2\npm - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-angular2.bat b/bin/windows/typescript-angular2.bat deleted file mode 100755 index ce2f0e0dc8c..00000000000 --- a/bin/windows/typescript-angular2.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-angular2 -o samples\client\petstore\typescript-angular2\default - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-fetch.bat b/bin/windows/typescript-fetch.bat deleted file mode 100755 index b3ff19ea211..00000000000 --- a/bin/windows/typescript-fetch.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-fetch -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-fetch -o samples\client\petstore\typescript-fetch - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-node-with-npm.bat b/bin/windows/typescript-node-with-npm.bat deleted file mode 100755 index a433181fde9..00000000000 --- a/bin/windows/typescript-node-with-npm.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-node -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -c bin/typescript-petstore-npm.json -l typescript-node -o samples\client\petstore\typescript-node\npm - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-node.bat b/bin/windows/typescript-node.bat deleted file mode 100755 index 53f8b34e843..00000000000 --- a/bin/windows/typescript-node.bat +++ /dev/null @@ -1,10 +0,0 @@ -set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar - -If Not Exist %executable% ( - mvn clean package -) - -set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-node -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-node -o samples\client\petstore\typescript-node\default - -java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 92490778689..6b56d5a6f56 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.2-SNAPSHOT ../.. 4.0.0 @@ -18,6 +18,7 @@ src/main/resources + true logback.xml diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 98c0b8c05b5..94b64be8d02 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -6,6 +6,7 @@ import io.swagger.codegen.cmd.Generate; import io.swagger.codegen.cmd.Langs; import io.swagger.codegen.cmd.Meta; +import io.swagger.codegen.cmd.Version; /** * User: lanwen @@ -21,16 +22,20 @@ public class SwaggerCodegen { public static void main(String[] args) { + String version = Version.readVersionFromResources(); @SuppressWarnings("unchecked") Cli.CliBuilder builder = Cli.builder("swagger-codegen-cli") - .withDescription("Swagger code generator CLI. More info on swagger.io") + .withDescription(String.format( + "Swagger code generator CLI (version %s). More info on swagger.io", + version)) .withDefaultCommand(Langs.class) .withCommands( Generate.class, Meta.class, Langs.class, Help.class, - ConfigHelp.class + ConfigHelp.class, + Version.class ); builder.build().parse(args).run(); diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java index c2dffbe6200..3b5d71eec9f 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java @@ -68,12 +68,8 @@ public void run() { "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig") ); - String swaggerVersion = this.getClass().getPackage().getImplementationVersion(); - // if the code is running outside of the jar (i.e. from the IDE), it will not have the version available. - // let's default it with something. - if (swaggerVersion==null) { - swaggerVersion = "2.1.3"; - } + String swaggerVersion = Version.readVersionFromResources(); + Map data = new ImmutableMap.Builder() .put("generatorPackage", targetPackage) .put("generatorClass", mainClass) diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java new file mode 100644 index 00000000000..c39b54a30a3 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java @@ -0,0 +1,45 @@ +package io.swagger.codegen.cmd; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import io.airlift.airline.Command; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Command(name = "version", description = "Show version information") +public class Version implements Runnable { + + private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class); + + private static final String VERSION_PLACEHOLDER = "${project.version}"; + + private static final String UNREADABLE_VERSION = "unreadable"; + private static final String UNSET_VERSION = "unset"; + private static final String UNKNOWN_VERSION = "unknown"; + + public static String readVersionFromResources() { + Properties versionProperties = new Properties(); + try (InputStream is = Version.class.getResourceAsStream("/version.properties")) { + versionProperties.load(is); + } catch (IOException ex) { + LOGGER.error("Error loading version properties", ex); + return UNREADABLE_VERSION; + } + + String version = versionProperties.getProperty("version", UNKNOWN_VERSION).trim(); + if (VERSION_PLACEHOLDER.equals(version)) { + return UNSET_VERSION; + } else { + return version; + } + } + + @Override + public void run() { + String version = readVersionFromResources(); + System.out.println(version); + } + +} diff --git a/modules/swagger-codegen-cli/src/main/resources/version.properties b/modules/swagger-codegen-cli/src/main/resources/version.properties new file mode 100644 index 00000000000..410af8cc687 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/resources/version.properties @@ -0,0 +1 @@ +version = ${project.version} diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md index d9282c97ebf..a7284fdb3c5 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.1.5-SNAPSHOT + 2.2.2-SNAPSHOT @@ -45,6 +45,7 @@ mvn clean compile - `modelPackage` - the package to use for generated model objects/classes - `apiPackage` - the package to use for generated api objects/classes - `invokerPackage` - the package to use for the generated invoker objects +- `modelNamePrefix` and `modelNameSuffix` - Sets the pre- or suffix for model classes and enums. - `configOptions` - a map of language-specific parameters (see below) - `configHelp` - dumps the configuration help for the specified library (generates no sources) diff --git a/modules/swagger-codegen-maven-plugin/examples/java-client.xml b/modules/swagger-codegen-maven-plugin/examples/java-client.xml index 5c093372f3b..b14c33e9424 100644 --- a/modules/swagger-codegen-maven-plugin/examples/java-client.xml +++ b/modules/swagger-codegen-maven-plugin/examples/java-client.xml @@ -12,7 +12,7 @@ io.swagger swagger-codegen-maven-plugin - 2.1.5-SNAPSHOT + 2.2.2-SNAPSHOT @@ -112,4 +112,4 @@ 1.0.0 4.8.1 - \ No newline at end of file + diff --git a/modules/swagger-codegen-maven-plugin/examples/swagger.yaml b/modules/swagger-codegen-maven-plugin/examples/swagger.yaml index c6eeffab7d7..c6d37b25750 100644 --- a/modules/swagger-codegen-maven-plugin/examples/swagger.yaml +++ b/modules/swagger-codegen-maven-plugin/examples/swagger.yaml @@ -93,7 +93,7 @@ paths: tags: - "pet" summary: "Finds Pets by status" - description: "Multiple status values can be provided with comma seperated strings" + description: "Multiple status values can be provided with comma separated strings" operationId: "findPetsByStatus" produces: - "application/xml" @@ -130,7 +130,7 @@ paths: tags: - "pet" summary: "Finds Pets by tags" - description: "Muliple tags can be provided with comma seperated strings. Use\ + description: "Multiple tags can be provided with comma separated strings. Use\ \ tag1, tag2, tag3 for testing." operationId: "findPetsByTags" produces: diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 0b6885bf048..4df64ca4e61 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.2-SNAPSHOT ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 261d539e2e5..fabd2947298 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -21,8 +21,6 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.config.CodegenConfigurator; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -32,9 +30,7 @@ import java.io.File; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; import static io.swagger.codegen.config.CodegenConfiguratorUtils.*; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @@ -135,6 +131,18 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "library", required = false) private String library; + /** + * Sets the prefix for model enums and classes + */ + @Parameter(name = "modelNamePrefix", required = false) + private String modelNamePrefix; + + /** + * Sets the suffix for model enums and classes + */ + @Parameter(name = "modelNameSuffix", required = false) + private String modelNameSuffix; + /** * A map of language-specific parameters as passed with the -c option to the command line */ @@ -217,6 +225,14 @@ public void execute() throws MojoExecutionException { configurator.setLibrary(library); } + if(isNotEmpty(modelNamePrefix)) { + configurator.setModelNamePrefix(modelNamePrefix); + } + + if(isNotEmpty(modelNameSuffix)) { + configurator.setModelNameSuffix(modelNameSuffix); + } + if (null != templateDirectory) { configurator.setTemplateDir(templateDirectory.getAbsolutePath()); } diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 8f7e98074de..21e44ce2547 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.2-SNAPSHOT ../.. 4.0.0 @@ -25,17 +25,17 @@ org.jvnet.wagon-svn wagon-svn - 1.8 + 1.12 org.apache.maven.wagon wagon-ssh-external - 1.0-alpha-6 + 2.10 org.apache.maven.wagon wagon-webdav - 1.0-beta-1 + 1.0-beta-2 target @@ -44,7 +44,7 @@ org.codehaus.mojo exec-maven-plugin - 1.3.2 + 1.5.0 @@ -72,16 +72,16 @@ maven-compiler-plugin - 3.0 + 3.5.1 - 1.6 - 1.6 + 1.7 + 1.7 org.apache.maven.plugins maven-jar-plugin - 2.4 + 3.0.2 @@ -92,21 +92,6 @@ - - - org.apache.maven.plugins - maven-site-plugin - 2.1 - - - org.apache.maven.plugins - maven-release-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 @@ -117,11 +102,13 @@ org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - + maven-site-plugin + 3.5.1 + + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 @@ -166,7 +153,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.9 + 2.10.4 true true @@ -180,7 +167,7 @@ org.apache.maven.plugins maven-jxr-plugin - 2.3 + 2.5 true @@ -188,7 +175,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 2.6 + 2.9 @@ -200,7 +187,7 @@ - 1.2.1 + 1.3.0 diff --git a/modules/swagger-codegen/src/main/java/config/ConfigParser.java b/modules/swagger-codegen/src/main/java/config/ConfigParser.java index 68cbb613f3a..0cd2558e266 100644 --- a/modules/swagger-codegen/src/main/java/config/ConfigParser.java +++ b/modules/swagger-codegen/src/main/java/config/ConfigParser.java @@ -27,7 +27,7 @@ public static Config read(String location) { Iterator> optionNodes = rootNode.fields(); while (optionNodes.hasNext()) { - Map.Entry optionNode = (Map.Entry) optionNodes.next(); + Map.Entry optionNode = optionNodes.next(); if (optionNode.getValue().isValueNode()) { config.setOption(optionNode.getKey(), optionNode.getValue().asText()); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index 649f068d16c..c4f0dc1ce7a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -2,7 +2,6 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; @@ -124,9 +123,8 @@ public static void main(String[] args) { public static List getExtensions() { ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); List output = new ArrayList(); - Iterator itr = loader.iterator(); - while (itr.hasNext()) { - output.add(itr.next()); + for (CodegenConfig aLoader : loader) { + output.add(aLoader); } return output; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 2e8245f53f5..4b0ef89593f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -10,6 +10,8 @@ import java.util.Map; import java.util.Set; +import com.samskivert.mustache.Mustache.Compiler; + public interface CodegenConfig { CodegenType getTag(); @@ -77,6 +79,10 @@ public interface CodegenConfig { List supportingFiles(); + String getInputSpec(); + + void setInputSpec(String inputSpec); + String getOutputDir(); void setOutputDir(String dir); @@ -117,6 +123,8 @@ public interface CodegenConfig { void processSwagger(Swagger swagger); + Compiler processCompiler(Compiler compiler); + String sanitizeTag(String tag); String toApiFilename(String name); 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 df62dcc1937..7a10c3f3ac6 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 @@ -127,4 +127,10 @@ public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case public static final String GENERATE_MODEL_TESTS = "generateModelTests"; public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated."; + public static final String HIDE_GENERATION_TIMESTAMP = "hideGenerationTimestamp"; + public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp."; + + public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged"; + public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events."; + } 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 6d32d54f3f9..118de425c93 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 @@ -18,7 +18,7 @@ public class CodegenModel { public CodegenModel parentModel; public List interfaceModels; - public String name, classname, description, classVarName, modelJson, dataType; + public String name, classname, title, description, classVarName, modelJson, dataType; public String classFilename; // store the class file name, mainly used for import public String unescapedDescription; public String discriminator; @@ -80,6 +80,8 @@ public boolean equals(Object o) { return false; if (classname != null ? !classname.equals(that.classname) : that.classname != null) return false; + if (title != null ? !title.equals(that.title) : that.title != null) + return false; if (description != null ? !description.equals(that.description) : that.description != null) return false; if (classVarName != null ? !classVarName.equals(that.classVarName) : that.classVarName != null) @@ -143,6 +145,7 @@ public int hashCode() { result = 31 * result + (interfaceModels != null ? interfaceModels.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (classname != null ? classname.hashCode() : 0); + result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (classVarName != null ? classVarName.hashCode() : 0); result = 31 * result + (modelJson != null ? modelJson.hashCode() : 0); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java index 4c2b4d4eb87..d0a93731a30 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java @@ -30,9 +30,7 @@ public static T newInstance(CodegenModelType type) { Class classType = typeMapping.get(type); try { return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException(e); } } 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 e92e8aeb1d1..501479955fd 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 @@ -281,7 +281,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = responseHeaders != null ? responseHeaders.hashCode() : 0; + int result = responseHeaders.hashCode(); result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0); result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0); result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0); 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 7462094acc2..b6a4b9d02da 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 @@ -46,6 +46,8 @@ public class CodegenProperty implements Cloneable { public Boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template) public Boolean isInherited; public String nameInCamelCase; // property name in camel case + // enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1) + public String enumName; @Override public String toString() { @@ -111,6 +113,7 @@ public int hashCode() result = prime * result + ((isListContainer == null) ? 0 : isListContainer.hashCode()); result = prime * result + Objects.hashCode(isInherited); result = prime * result + Objects.hashCode(nameInCamelCase); + result = prime * result + Objects.hashCode(enumName); return result; } @@ -271,6 +274,9 @@ public boolean equals(Object obj) { if (!Objects.equals(this.nameInCamelCase, other.nameInCamelCase)) { return false; } + if (!Objects.equals(this.enumName, other.enumName)) { + return false; + } return true; } 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 746f65cea38..a8a2117a31e 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 @@ -35,7 +35,7 @@ public boolean equals(Object o) { CodegenResponse that = (CodegenResponse) o; - if (headers != null ? !headers.equals(that.headers) : that.headers != null) + if (!headers.equals(that.headers)) return false; if (code != null ? !code.equals(that.code) : that.code != null) return false; @@ -71,7 +71,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = headers != null ? headers.hashCode() : 0; + int result = headers.hashCode(); result = 31 * result + (code != null ? code.hashCode() : 0); result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index 2e33242c370..4e9dd098a4e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -13,6 +13,7 @@ public class CodegenSecurity { // Oauth specific public String flow, authorizationUrl, tokenUrl; public List> scopes; + public Boolean isCode, isPassword, isApplication, isImplicit; @Override public String toString() { @@ -50,6 +51,14 @@ public boolean equals(Object o) { return false; if (tokenUrl != null ? !tokenUrl.equals(that.tokenUrl) : that.tokenUrl != null) return false; + if (isCode != null ? !isCode.equals(that.isCode) : that.isCode != null) + return false; + if (isPassword != null ? !isPassword.equals(that.isPassword) : that.isPassword != null) + return false; + if (isApplication != null ? !isApplication.equals(that.isApplication) : that.isApplication != null) + return false; + if (isImplicit != null ? !isImplicit.equals(that.isImplicit) : that.isImplicit != null) + return false; return scopes != null ? scopes.equals(that.scopes) : that.scopes == null; } @@ -68,6 +77,10 @@ public int hashCode() { result = 31 * result + (flow != null ? flow.hashCode() : 0); result = 31 * result + (authorizationUrl != null ? authorizationUrl.hashCode() : 0); result = 31 * result + (tokenUrl != null ? tokenUrl.hashCode() : 0); + result = 31 * result + (isCode != null ? isCode.hashCode() : 0); + result = 31 * result + (isPassword != null ? isPassword.hashCode() : 0); + result = 31 * result + (isApplication != null ? isApplication.hashCode() : 0); + result = 31 * result + (isImplicit != null ? isImplicit.hashCode() : 0); result = 31 * result + (scopes != null ? scopes.hashCode() : 0); return result; } 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 786119b49f8..173a37e2528 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,6 +2,8 @@ import com.google.common.base.Function; import com.google.common.collect.Lists; +import com.samskivert.mustache.Mustache.Compiler; + import io.swagger.codegen.examples.ExampleGenerator; import io.swagger.models.ArrayModel; import io.swagger.models.ComposedModel; @@ -71,7 +73,8 @@ public class DefaultCodegen { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); - + + protected String inputSpec; protected String outputFolder = ""; protected Set defaultIncludes = new HashSet(); protected Map typeMapping = new HashMap(); @@ -97,16 +100,18 @@ public class DefaultCodegen { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean supportsInheritance; + protected boolean supportsMixins; protected Map supportedLibraries = new LinkedHashMap(); protected String library; protected Boolean sortParamsByRequiredFlag = true; protected Boolean ensureUniqueParams = true; protected String gitUserId, gitRepoId, releaseNote; protected String httpUserAgent; + protected Boolean hideGenerationTimestamp = true; // How to encode special characters like $ // They are translated to words like "Dollar" and prefixed with ' // Then translated back during JSON encoding and decoding - protected Map specialCharReplacements = new HashMap(); + protected Map specialCharReplacements = new HashMap(); public List cliOptions() { return cliOptions; @@ -253,7 +258,7 @@ public String findCommonPrefixOfVars(List vars) { } /** - * Return the enum default value in the language specifed format + * Return the enum default value in the language specified format * * @param value enum variable name * @param datatype data type @@ -264,7 +269,7 @@ public String toEnumDefaultValue(String value, String datatype) { } /** - * Return the enum value in the language specifed format + * Return the enum value in the language specified format * e.g. status becomes "status" * * @param value enum variable name @@ -326,6 +331,12 @@ public void preprocessSwagger(Swagger swagger) { @SuppressWarnings("unused") public void processSwagger(Swagger swagger) { } + + // override with any special handling of the JMustache compiler + @SuppressWarnings("unused") + public Compiler processCompiler(Compiler compiler) { + return compiler; + } // override with any special text escaping logic @SuppressWarnings("static-method") @@ -349,7 +360,7 @@ public String escapeText(String input) { * @return string with unsafe characters removed or escaped */ public String escapeUnsafeCharacters(String input) { - LOGGER.warn("escapeUnsafeCharacters should be overriden in the code generator with proper logic to escape unsafe characters"); + LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape unsafe characters"); // doing nothing by default and code generator should implement // the logic to prevent code injection // later we'll make this method abstract to make sure @@ -363,7 +374,7 @@ public String escapeUnsafeCharacters(String input) { * @return string with quotation mark removed or escaped */ public String escapeQuotationMark(String input) { - LOGGER.warn("escapeQuotationMark should be overriden in the code generator with proper logic to escape single/double quote"); + LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape single/double quote"); return input.replace("\"", "\\\""); } @@ -499,6 +510,14 @@ public String getOutputDir() { return outputFolder(); } + public String getInputSpec() { + return inputSpec; + } + + public void setInputSpec(String inputSpec) { + this.inputSpec = inputSpec; + } + public void setTemplateDir(String templateDir) { this.templateDir = templateDir; } @@ -534,7 +553,7 @@ public void setEnsureUniqueParams(Boolean ensureUniqueParams) { * @return properly-escaped pattern */ public String toRegularExpression(String pattern) { - return escapeText(pattern); + return escapeText(addRegularExpressionDelimiter(pattern)); } /** @@ -780,30 +799,60 @@ public DefaultCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); - // initalize special character mapping + // initialize special character mapping initalizeSpecialCharacterMapping(); } /** - * Initalize special character mapping + * Initialize special character mapping */ protected void initalizeSpecialCharacterMapping() { // Initialize special characters - specialCharReplacements.put('$', "Dollar"); - specialCharReplacements.put('^', "Caret"); - specialCharReplacements.put('|', "Pipe"); - specialCharReplacements.put('=', "Equal"); - specialCharReplacements.put('*', "Star"); - specialCharReplacements.put('-', "Minus"); - specialCharReplacements.put('&', "Ampersand"); - specialCharReplacements.put('%', "Percent"); - specialCharReplacements.put('#', "Hash"); - specialCharReplacements.put('@', "At"); - specialCharReplacements.put('!', "Exclamation"); - specialCharReplacements.put('+', "Plus"); - specialCharReplacements.put(':', "Colon"); - specialCharReplacements.put('>', "GreaterThan"); - specialCharReplacements.put('<', "LessThan"); + specialCharReplacements.put("$", "Dollar"); + specialCharReplacements.put("^", "Caret"); + specialCharReplacements.put("|", "Pipe"); + specialCharReplacements.put("=", "Equal"); + specialCharReplacements.put("*", "Star"); + specialCharReplacements.put("-", "Minus"); + specialCharReplacements.put("&", "Ampersand"); + specialCharReplacements.put("%", "Percent"); + specialCharReplacements.put("#", "Hash"); + specialCharReplacements.put("@", "At"); + specialCharReplacements.put("!", "Exclamation"); + specialCharReplacements.put("+", "Plus"); + specialCharReplacements.put(":", "Colon"); + specialCharReplacements.put(">", "Greater_Than"); + specialCharReplacements.put("<", "Less_Than"); + specialCharReplacements.put(".", "Period"); + specialCharReplacements.put("_", "Underscore"); + specialCharReplacements.put("?", "Question_Mark"); + specialCharReplacements.put(",", "Comma"); + specialCharReplacements.put("'", "Quote"); + specialCharReplacements.put("\"", "Double_Quote"); + specialCharReplacements.put("/", "Slash"); + specialCharReplacements.put("\\", "Back_Slash"); + specialCharReplacements.put("(", "Left_Parenthesis"); + specialCharReplacements.put(")", "Right_Parenthesis"); + specialCharReplacements.put("{", "Left_Curly_Bracket"); + specialCharReplacements.put("}", "Right_Curly_Bracket"); + specialCharReplacements.put("[", "Left_Square_Bracket"); + specialCharReplacements.put("]", "Right_Square_Bracket"); + specialCharReplacements.put("~", "Tilde"); + specialCharReplacements.put("`", "Backtick"); + + specialCharReplacements.put("<=", "Less_Than_Or_Equal_To"); + specialCharReplacements.put(">=", "Greater_Than_Or_Equal_To"); + specialCharReplacements.put("!=", "Not_Equal"); + } + + /** + * Return the symbol name of a symbol + * + * @param input Symbol (e.g. $) + * @return Symbol name (e.g. Dollar) + */ + protected String getSymbolName(String input) { + return specialCharReplacements.get(input); } /** @@ -838,7 +887,7 @@ public String generateExamplePath(String path, Operation operation) { paramPart.append(param.getName()).append("="); paramPart.append("{"); if (qp.getCollectionFormat() != null) { - paramPart.append(param.getName() + "1"); + paramPart.append(param.getName()).append("1"); if ("csv".equals(qp.getCollectionFormat())) { paramPart.append(","); } else if ("pipes".equals(qp.getCollectionFormat())) { @@ -847,7 +896,7 @@ public String generateExamplePath(String path, Operation operation) { paramPart.append("\t"); } else if ("multi".equals(qp.getCollectionFormat())) { paramPart.append("&").append(param.getName()).append("="); - paramPart.append(param.getName() + "2"); + paramPart.append(param.getName()).append("2"); } } else { paramPart.append(param.getName()); @@ -1157,6 +1206,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe } else { m.name = name; } + m.title = escapeText(model.getTitle()); m.description = escapeText(model.getDescription()); m.unescapedDescription = model.getDescription(); m.classname = toModelName(name); @@ -1186,7 +1236,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe List required = new ArrayList(); Map allProperties; List allRequired; - if (supportsInheritance) { + if (supportsInheritance || supportsMixins) { allProperties = new LinkedHashMap(); allRequired = new ArrayList(); m.allVars = new ArrayList(); @@ -1195,7 +1245,38 @@ public CodegenModel fromModel(String name, Model model, Map allDe allRequired = null; } // parent model - final RefModel parent = (RefModel) composed.getParent(); + RefModel parent = (RefModel) composed.getParent(); + + // interfaces (intermediate models) + if (composed.getInterfaces() != null) { + if (m.interfaces == null) + m.interfaces = new ArrayList(); + for (RefModel _interface : composed.getInterfaces()) { + Model interfaceModel = null; + if (allDefinitions != null) { + interfaceModel = allDefinitions.get(_interface.getSimpleRef()); + } + // set first interface with discriminator found as parent + if (parent == null + && ((interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) + || (interfaceModel instanceof ComposedModel && isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions)))) { + parent = _interface; + } else { + final String interfaceRef = toModelName(_interface.getSimpleRef()); + m.interfaces.add(interfaceRef); + addImport(m, interfaceRef); + if (allDefinitions != null) { + if (!supportsMixins) { + addProperties(properties, required, interfaceModel, allDefinitions); + } + if (supportsInheritance) { + addProperties(allProperties, allRequired, interfaceModel, allDefinitions); + } + } + } + } + } + if (parent != null) { final String parentRef = parent.getSimpleRef(); m.parentSchema = parentRef; @@ -1210,24 +1291,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe } } } - // interfaces (intermediate models) - if (composed.getInterfaces() != null) { - if (m.interfaces == null) - m.interfaces = new ArrayList(); - for (RefModel _interface : composed.getInterfaces()) { - final String interfaceRef = toModelName(_interface.getSimpleRef()); - m.interfaces.add(interfaceRef); - addImport(m, interfaceRef); - if (allDefinitions != null) { - final Model interfaceModel = allDefinitions.get(_interface.getSimpleRef()); - if (supportsInheritance) { - addProperties(allProperties, allRequired, interfaceModel, allDefinitions); - } else { - addProperties(properties, required, interfaceModel, allDefinitions); - } - } - } - } + // child model (properties owned by the model itself) Model child = composed.getChild(); if (child != null && child instanceof RefModel && allDefinitions != null) { @@ -1265,6 +1329,30 @@ public CodegenModel fromModel(String name, Model model, Map allDe return m; } + /** + * Recursively look for a discriminator in the interface tree + */ + private boolean isDiscriminatorInInterfaceTree(ComposedModel model, Map allDefinitions) { + if (model == null || allDefinitions == null) + return false; + + Model child = ((ComposedModel) model).getChild(); + if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) { + return true; + } + for (RefModel _interface : model.getInterfaces()) { + Model interfaceModel = allDefinitions.get(_interface.getSimpleRef()); + if (interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) { + return true; + } + if (interfaceModel instanceof ComposedModel) { + + return isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions); + } + } + return false; + } + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { MapProperty mapProperty = new MapProperty(swaggerModel.getAdditionalProperties()); addParentContainer(codegenModel, codegenModel.name, mapProperty); @@ -1323,7 +1411,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.name = toVarName(name); property.baseName = name; - property.nameInCamelCase = camelize(name, false); + property.nameInCamelCase = camelize(property.name, false); property.description = escapeText(p.getDescription()); property.unescapedDescription = p.getDescription(); property.getter = "get" + getterAndSetterCapitalize(name); @@ -1344,7 +1432,8 @@ public CodegenProperty fromProperty(String name, Property p) { property.exclusiveMaximum = np.getExclusiveMaximum(); // check if any validation rule defined - if (property.minimum != null || property.maximum != null || property.exclusiveMinimum != null || property.exclusiveMaximum != null) + // exclusive* are noop without corresponding min/max + if (property.minimum != null || property.maximum != null) property.hasValidation = true; // legacy support @@ -1514,7 +1603,7 @@ public CodegenProperty fromProperty(String name, Property p) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(String i : _enum) { - property._enum.add(i.toString()); + property._enum.add(i); } property.isEnum = true; @@ -1532,7 +1621,7 @@ public CodegenProperty fromProperty(String name, Property p) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(String i : _enum) { - property._enum.add(i.toString()); + property._enum.add(i); } property.isEnum = true; @@ -1548,6 +1637,7 @@ public CodegenProperty fromProperty(String name, Property p) { // this can cause issues for clients which don't support enums if (property.isEnum) { property.datatypeWithEnum = toEnumName(property); + property.enumName = toEnumName(property); } else { property.datatypeWithEnum = property.datatype; } @@ -1595,11 +1685,14 @@ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty property.items = innerProperty; // inner item is Enum if (isPropertyInnerMostEnum(property)) { + // isEnum is set to true when the type is an enum + // or the inner type of an array/map is an enum property.isEnum = true; // update datatypeWithEnum and default value for array // e.g. List => List updateDataTypeWithEnumForArray(property); - + // set allowable values to enum values (including array/map of enum) + property.allowableValues = getInnerEnumAllowableValues(property); } } } @@ -1622,10 +1715,14 @@ protected void updatePropertyForMap(CodegenProperty property, CodegenProperty in property.items = innerProperty; // inner item is Enum if (isPropertyInnerMostEnum(property)) { + // isEnum is set to true when the type is an enum + // or the inner type of an array/map is an enum property.isEnum = true; // update datatypeWithEnum and default value for map // e.g. Dictionary => Dictionary updateDataTypeWithEnumForMap(property); + // set allowable values to enum values (including array/map of enum) + property.allowableValues = getInnerEnumAllowableValues(property); } } @@ -1646,6 +1743,17 @@ protected Boolean isPropertyInnerMostEnum(CodegenProperty property) { return currentProperty.isEnum; } + protected Map getInnerEnumAllowableValues(CodegenProperty property) { + CodegenProperty currentProperty = property; + while (currentProperty != null && (Boolean.TRUE.equals(currentProperty.isMapContainer) + || Boolean.TRUE.equals(currentProperty.isListContainer))) { + currentProperty = currentProperty.items; + } + + return currentProperty.allowableValues; + } + + /** * Update datatypeWithEnum for array container * @param property Codegen property @@ -1659,9 +1767,13 @@ protected void updateDataTypeWithEnumForArray(CodegenProperty property) { // set both datatype and datetypeWithEnum as only the inner type is enum property.datatypeWithEnum = property.datatypeWithEnum.replace(baseItem.baseType, toEnumName(baseItem)); + // naming the enum with respect to the language enum naming convention + // e.g. remove [], {} from array/map of enum + property.enumName = toEnumName(property); + // set default value for variable with inner enum if (property.defaultValue != null) { - property.defaultValue = property.defaultValue.replace(property.items.baseType, toEnumName(property.items)); + property.defaultValue = property.defaultValue.replace(baseItem.baseType, toEnumName(baseItem)); } } @@ -1678,6 +1790,10 @@ protected void updateDataTypeWithEnumForMap(CodegenProperty property) { // set both datatype and datetypeWithEnum as only the inner type is enum property.datatypeWithEnum = property.datatypeWithEnum.replace(", " + baseItem.baseType, ", " + toEnumName(baseItem)); + // naming the enum with respect to the language enum naming convention + // e.g. remove [], {} from array/map of enum + property.enumName = toEnumName(property); + // set default value for variable with inner enum if (property.defaultValue != null) { property.defaultValue = property.defaultValue.replace(", " + property.items.baseType, ", " + toEnumName(property.items)); @@ -1774,7 +1890,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation for (String key : consumes) { Map mediaType = new HashMap(); // escape quotation to avoid code injection - mediaType.put("mediaType", escapeQuotationMark(key)); + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); count += 1; if (count < consumes.size()) { mediaType.put("hasMore", "true"); @@ -1808,7 +1924,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation for (String key : produces) { Map mediaType = new HashMap(); // escape quotation to avoid code injection - mediaType.put("mediaType", escapeQuotationMark(key)); + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); count += 1; if (count < produces.size()) { mediaType.put("hasMore", "true"); @@ -2184,8 +2300,8 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.uniqueItems = qp.isUniqueItems(); p.multipleOf = qp.getMultipleOf(); - if (p.maximum != null || p.exclusiveMaximum != null || - p.minimum != null || p.exclusiveMinimum != null || + // exclusive* are noop without corresponding min/max + if (p.maximum != null || p.minimum != null || p.maxLength != null || p.minLength != null || p.maxItems != null || p.minItems != null || p.pattern != null) { @@ -2268,28 +2384,28 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { } else if (Boolean.TRUE.equals(p.isString)) { p.example = p.paramName + "_example"; } else if (Boolean.TRUE.equals(p.isBoolean)) { - p.example = new String("true"); + p.example = "true"; } else if (Boolean.TRUE.equals(p.isLong)) { - p.example = new String("789"); + p.example = "789"; } else if (Boolean.TRUE.equals(p.isInteger)) { - p.example = new String("56"); + p.example = "56"; } else if (Boolean.TRUE.equals(p.isFloat)) { - p.example = new String("3.4"); + p.example = "3.4"; } else if (Boolean.TRUE.equals(p.isDouble)) { - p.example = new String("1.2"); + p.example = "1.2"; } else if (Boolean.TRUE.equals(p.isBinary)) { - p.example = new String("BINARY_DATA_HERE"); + p.example = "BINARY_DATA_HERE"; } else if (Boolean.TRUE.equals(p.isByteArray)) { - p.example = new String("B"); + p.example = "B"; } else if (Boolean.TRUE.equals(p.isDate)) { - p.example = new String("2013-10-20"); + p.example = "2013-10-20"; } else if (Boolean.TRUE.equals(p.isDateTime)) { - p.example = new String("2013-10-20T19:20:30+01:00"); + p.example = "2013-10-20T19:20:30+01:00"; } else if (param instanceof FormParameter && ("file".equalsIgnoreCase(((FormParameter) param).getType()) || "file".equals(p.baseType))) { p.isFile = true; - p.example = new String("/path/to/file.txt"); + p.example = "/path/to/file.txt"; } // set the parameter excample value @@ -2351,6 +2467,7 @@ public List fromSecurity(Map CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); sec.name = entry.getKey(); sec.type = schemeDefinition.getType(); + sec.isCode = sec.isPassword = sec.isApplication = sec.isImplicit = false; if (schemeDefinition instanceof ApiKeyAuthDefinition) { final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition; @@ -2367,6 +2484,25 @@ public List fromSecurity(Map sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); + if (sec.flow == null) { + throw new RuntimeException("missing oauth flow in " + sec.name); + } + switch(sec.flow) { + case "accessCode": + sec.isCode = true; + break; + case "password": + sec.isPassword = true; + break; + case "application": + sec.isApplication = true; + break; + case "implicit": + sec.isImplicit = true; + break; + default: + throw new RuntimeException("unknown oauth flow: " + sec.flow); + } sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); sec.tokenUrl = oauth2Definition.getTokenUrl(); if (oauth2Definition.getScopes() != null) { @@ -2375,7 +2511,7 @@ public List fromSecurity(Map for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { Map scope = new HashMap(); scope.put("scope", scopeEntry.getKey()); - scope.put("description", scopeEntry.getValue()); + scope.put("description", escapeText(scopeEntry.getValue())); count += 1; if (count < numScopes) { @@ -2427,8 +2563,7 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri // must be root tmpPath builder.append("root"); } - for (int i = 0; i < parts.length; i++) { - String part = parts[i]; + for (String part : parts) { if (part.length() > 0) { if (builder.toString().length() == 0) { part = Character.toLowerCase(part.charAt(0)) + part.substring(1); @@ -2483,10 +2618,10 @@ private static List addHasMore(List objs) { if (objs != null) { for (int i = 0; i < objs.size(); i++) { if (i > 0) { - objs.get(i).secondaryParam = new Boolean(true); + objs.get(i).secondaryParam = true; } if (i < objs.size() - 1) { - objs.get(i).hasMore = new Boolean(true); + objs.get(i).hasMore = true; } } } @@ -2497,7 +2632,7 @@ private static Map addHasMore(Map objs) { if (objs != null) { for (int i = 0; i < objs.size() - 1; i++) { if (i > 0) { - objs.put("secondaryParam", new Boolean(true)); + objs.put("secondaryParam", true); } if (i < objs.size() - 1) { objs.put("hasMore", true); @@ -3069,7 +3204,7 @@ public void writeOptional(String outputFolder, SupportingFile supportingFile) { */ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter parameter, CodegenProperty property) { if (parameter == null) { - LOGGER.error("Codegen Parameter cannnot be null."); + LOGGER.error("Codegen Parameter cannot be null."); return; } @@ -3171,4 +3306,19 @@ public void updateCodegenPropertyEnum(CodegenProperty var) { } } } + + /** + * If the pattern misses the delimiter, add "/" to the beginning and end + * Otherwise, return the original pattern + * + * @param pattern the pattern (regular expression) + * @return the pattern with delimiter + */ + public String addRegularExpressionDelimiter(String pattern) { + if (pattern != null && !pattern.matches("^/.*")) { + return "/" + pattern + "/"; + } + + return pattern; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b0cb8d1006c..fd893f5d52f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -17,7 +17,7 @@ import java.io.*; import java.util.*; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import org.apache.commons.lang3.StringUtils; public class DefaultGenerator extends AbstractGenerator implements Generator { protected Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); @@ -140,7 +140,8 @@ public List generate() { config.additionalProperties().put("generatedDate", DateTime.now().toString()); config.additionalProperties().put("generatorClass", config.getClass().toString()); - + config.additionalProperties().put("inputSpec", config.getInputSpec()); + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (info.getTitle() != null) { @@ -149,10 +150,16 @@ public List generate() { if (info.getVersion() != null) { config.additionalProperties().put("appVersion", config.escapeText(info.getVersion())); } - if (info.getDescription() != null) { + + if (StringUtils.isEmpty(info.getDescription())) { + // set a default description if none if provided + config.additionalProperties().put("appDescription", + "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); + } else { config.additionalProperties().put("appDescription", config.escapeText(info.getDescription())); } + if (info.getContact() != null) { Contact contact = info.getContact(); config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl())); @@ -259,7 +266,10 @@ private int getInheritanceDepth(Model model) { private Model getParent(Model model) { if (model instanceof ComposedModel) { - return definitions.get(((ComposedModel) model).getParent().getReference()); + Model parent = ((ComposedModel) model).getParent(); + if(parent != null) { + return definitions.get(parent.getReference()); + } } return null; @@ -271,6 +281,7 @@ private Model getParent(Model model) { try { //don't generate models that have an import mapping if(config.importMapping().containsKey(name)) { + LOGGER.info("Model " + name + " not imported due to import mapping"); continue; } @@ -284,7 +295,7 @@ private Model getParent(Model model) { allProcessedModels.put(name, models); } catch (Exception e) { - throw new RuntimeException("Could not process model '" + name + "'", e); + throw new RuntimeException("Could not process model '" + name + "'" + ".Please make sure that your schema is correct!", e); } } @@ -402,7 +413,7 @@ public int compare(CodegenOperation one, CodegenOperation another) { // Pass sortParamsByRequiredFlag through to the Mustache template... boolean sortParamsByRequiredFlag = true; if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - sortParamsByRequiredFlag = Boolean.valueOf((String)this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); + sortParamsByRequiredFlag = Boolean.valueOf(this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); } operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); @@ -496,6 +507,13 @@ public int compare(CodegenOperation one, CodegenOperation another) { bundle.put("modelPackage", config.modelPackage()); List authMethods = config.fromSecurity(swagger.getSecurityDefinitions()); if (authMethods != null && !authMethods.isEmpty()) { + // sort auth methods to maintain the same order + Collections.sort(authMethods, new Comparator() { + @Override + public int compare(CodegenSecurity one, CodegenSecurity another) { + return ObjectUtils.compare(one.name, another.name); + } + }); bundle.put("authMethods", authMethods); bundle.put("hasAuthMethods", true); } @@ -519,7 +537,7 @@ public int compare(CodegenOperation one, CodegenOperation another) { for (SupportingFile support : config.supportingFiles()) { try { String outputFolder = config.outputFolder(); - if (isNotEmpty(support.folder)) { + if (StringUtils.isNotEmpty(support.folder)) { outputFolder += File.separator + support.folder; } File of = new File(outputFolder); @@ -550,7 +568,9 @@ public int compare(CodegenOperation one, CodegenOperation another) { if(ignoreProcessor.allowsFile(new File(outputFilename))) { if (templateFile.endsWith("mustache")) { String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() + Mustache.Compiler compiler = Mustache.compiler(); + compiler = config.processCompiler(compiler); + Template tmpl = compiler .withLoader(new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { @@ -631,7 +651,9 @@ private File processTemplateToFile(Map templateData, String temp if(ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) { String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() + Mustache.Compiler compiler = Mustache.compiler(); + compiler = config.processCompiler(compiler); + Template tmpl = compiler .withLoader(new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { 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 e82f92b5024..34b0906fd10 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 @@ -45,27 +45,26 @@ public void flatten(Swagger swagger) { BodyParameter bp = (BodyParameter) parameter; if (bp.getSchema() != null) { Model model = bp.getSchema(); - if(model instanceof ModelImpl) { + if (model instanceof ModelImpl) { ModelImpl obj = (ModelImpl) model; if (obj.getType() == null || "object".equals(obj.getType())) { if (obj.getProperties() != null && obj.getProperties().size() > 0) { flattenProperties(obj.getProperties(), pathname); - String modelName = resolveModelName( obj.getTitle(), bp.getName()); + String modelName = resolveModelName(obj.getTitle(), bp.getName()); bp.setSchema(new RefModel(modelName)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } } - } - else if (model instanceof ArrayModel) { + } else if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; Property inner = am.getItems(); - if(inner instanceof ObjectProperty) { + if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName( op.getTitle(), bp.getName()); + String modelName = resolveModelName(op.getTitle(), bp.getName()); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { @@ -91,13 +90,13 @@ else if (model instanceof ArrayModel) { if (property instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) property; if (op.getProperties() != null && op.getProperties().size() > 0) { - String modelName = resolveModelName( op.getTitle(),"inline_response_" + key); + String modelName = resolveModelName(op.getTitle(), "inline_response_" + key); Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); if (existing != null) { - response.setSchema(new RefProperty(existing)); + response.setSchema(this.makeRefProperty(existing, property)); } else { - response.setSchema(new RefProperty(modelName)); + response.setSchema(this.makeRefProperty(modelName, property)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } @@ -106,41 +105,43 @@ else if (model instanceof ArrayModel) { ArrayProperty ap = (ArrayProperty) property; Property inner = ap.getItems(); - if(inner instanceof ObjectProperty) { + if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName( op.getTitle(),"inline_response_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - ap.setItems(new RefProperty(existing)); - } else { - ap.setItems(new RefProperty(modelName)); + if (op.getProperties() != null && op.getProperties().size() > 0) { + flattenProperties(op.getProperties(), pathname); + String modelName = resolveModelName(op.getTitle(), + "inline_response_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + ap.setItems(this.makeRefProperty(existing, op)); + } else { + ap.setItems(this.makeRefProperty(modelName, op)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); - } + } } } } else if (property instanceof MapProperty) { MapProperty mp = (MapProperty) property; Property innerProperty = mp.getAdditionalProperties(); - if(innerProperty instanceof ObjectProperty) { + if (innerProperty instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) innerProperty; if (op.getProperties() != null && op.getProperties().size() > 0) { - flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName( op.getTitle(),"inline_response_" + key); - Model innerModel = modelFromProperty(op, modelName); - String existing = matchGenerated(innerModel); - if (existing != null) { - mp.setAdditionalProperties(new RefProperty(existing)); - } else { - mp.setAdditionalProperties(new RefProperty(modelName)); - addGenerated(modelName, innerModel); - swagger.addDefinition(modelName, innerModel); - } - } + flattenProperties(op.getProperties(), pathname); + String modelName = resolveModelName(op.getTitle(), + "inline_response_" + key); + Model innerModel = modelFromProperty(op, modelName); + String existing = matchGenerated(innerModel); + if (existing != null) { + mp.setAdditionalProperties(new RefProperty(existing)); + } else { + mp.setAdditionalProperties(new RefProperty(modelName)); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } } } } @@ -167,7 +168,7 @@ else if (model instanceof ArrayModel) { if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { - String innerModelName = uniqueName(modelName + "_inner"); + String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner"); Model innerModel = modelFromProperty(op, innerModelName); String existing = matchGenerated(innerModel); if (existing == null) { @@ -179,18 +180,23 @@ else if (model instanceof ArrayModel) { } } } + } else if (model instanceof ComposedModel) { + ComposedModel m = (ComposedModel) model; + if (m.getChild() != null) { + Map properties = m.getChild().getProperties(); + flattenProperties(properties, modelName); + } } } } } - private String resolveModelName(String title, String key ) { - if (title == null) { - return uniqueName(key); - } - else { - return uniqueName(title); - } + private String resolveModelName(String title, String key) { + if (title == null) { + return uniqueName(key); + } else { + return uniqueName(title); + } } public String matchGenerated(Model model) { @@ -211,7 +217,11 @@ public void addGenerated(String name, Model model) { public String uniqueName(String key) { int count = 0; boolean done = false; - key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter + // should not be + // assigned. Also declare + // the methods parameters + // as 'final'. while (!done) { String name = key; if (count > 0) { @@ -235,12 +245,12 @@ public void flattenProperties(Map properties, String path) { Map modelsToAdd = new HashMap(); for (String key : properties.keySet()) { Property property = properties.get(key); - if (property instanceof ObjectProperty && - ((ObjectProperty)property).getProperties() != null && - ((ObjectProperty)property).getProperties().size() > 0) { - String modelName = uniqueName(path + "_" + key); + if (property instanceof ObjectProperty && ((ObjectProperty) property).getProperties() != null + && ((ObjectProperty) property).getProperties().size() > 0) { ObjectProperty op = (ObjectProperty) property; + + String modelName = resolveModelName(op.getTitle(), path + "_" + key); Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); @@ -261,7 +271,7 @@ public void flattenProperties(Map properties, String path) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), path); - String modelName = uniqueName(path + "_" + key); + String modelName = resolveModelName(op.getTitle(), path + "_" + key); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { @@ -281,7 +291,7 @@ public void flattenProperties(Map properties, String path) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), path); - String modelName = uniqueName(path + "_" + key); + String modelName = resolveModelName(op.getTitle(), path + "_" + key); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { @@ -312,9 +322,10 @@ public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String example = null; Object obj = object.getExample(); - if(obj != null) { + if (obj != null) { example = obj.toString(); } + Property inner = object.getItems(); if (inner instanceof ObjectProperty) { ArrayModel model = new ArrayModel(); @@ -323,6 +334,7 @@ public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") model.setItems(object.getItems()); return model; } + return null; } @@ -331,7 +343,7 @@ public Model modelFromProperty(ObjectProperty object, String path) { String example = null; Object obj = object.getExample(); - if(obj != null) { + if (obj != null) { example = obj.toString(); } String name = object.getName(); @@ -358,7 +370,7 @@ public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") S String example = null; Object obj = object.getExample(); - if(obj != null) { + if (obj != null) { example = obj.toString(); } @@ -370,6 +382,32 @@ public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") S return model; } + /** + * Make a RefProperty + * + * @param ref + * @param property + * @return + */ + public Property makeRefProperty(String ref, Property property) { + RefProperty newProperty = new RefProperty(ref); + this.copyVendorExtensions(property, newProperty); + return newProperty; + } + + /** + * Copy vendor extensions from Property to another Property + * + * @param source + * @param target + */ + public void copyVendorExtensions(Property source, AbstractProperty target) { + Map vendorExtensions = source.getVendorExtensions(); + for (String extName : vendorExtensions.keySet()) { + target.setVendorExtension(extName, vendorExtensions.get(extName)); + } + } + public boolean isSkipMatches() { return skipMatches; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java index 6bbc02130c7..45eb05e56fb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java @@ -16,7 +16,6 @@ import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; @@ -40,9 +39,8 @@ public static void main(String[] args) { public static List getExtensions() { ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); List output = new ArrayList(); - Iterator itr = loader.iterator(); - while (itr.hasNext()) { - output.add(itr.next()); + for (CodegenConfig config : loader) { + output.add(config); } return output; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 4ac39d5296f..1dd1ced4d74 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -151,7 +151,7 @@ public CodegenConfigurator setTemplateDir(String templateDir) { File f = new File(templateDir); // check to see if the folder exists - if (!(f != null && f.exists() && f.isDirectory())) { + if (!(f.exists() && f.isDirectory())) { throw new IllegalArgumentException("Template directory " + templateDir + " does not exist."); } @@ -352,6 +352,7 @@ public ClientOptInput toClientOptInput() { CodegenConfig config = CodegenConfigLoader.forName(lang); + config.setInputSpec(inputSpec); config.setOutputDir(outputDir); config.setSkipOverwrite(skipOverwrite); @@ -413,7 +414,7 @@ private void handleDynamicProperties(CodegenConfig codegenConfig) { codegenConfig.additionalProperties().put(opt, dynamicProperties.get(opt)); } else if(systemProperties.containsKey(opt)) { - codegenConfig.additionalProperties().put(opt, systemProperties.get(opt).toString()); + codegenConfig.additionalProperties().put(opt, systemProperties.get(opt)); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index 5c373607d53..228e5afb90d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -99,15 +99,15 @@ protected Object resolvePropertyToExample(String mediaType, Property property, S } else if (property instanceof DecimalProperty) { return new BigDecimal(1.3579); } else if (property instanceof DoubleProperty) { - return new Double(3.149); + return 3.149; } else if (property instanceof FileProperty) { return ""; // TODO } else if (property instanceof FloatProperty) { - return new Float(1.23); + return 1.23f; } else if (property instanceof IntegerProperty) { - return new Integer(123); + return 123; } else if (property instanceof LongProperty) { - return new Long(123456789); + return 123456789L; } else if (property instanceof MapProperty) { Map mp = new HashMap(); if (property.getName() != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java index 8d199cba763..137cb071cab 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java @@ -26,10 +26,8 @@ protected String getPattern() { if(syntax == null) return this.definition; StringBuilder sb = new StringBuilder(); - for (int i = 0; i < syntax.size(); i++) { - Part current = syntax.get(i); - - switch(current.getToken()){ + for (Part current : syntax) { + switch (current.getToken()) { case MATCH_ALL: case MATCH_ANY: case ESCAPED_EXCLAMATION: 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 0ea7b5b4855..da01ca6eae5 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 @@ -41,6 +41,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co public AbstractCSharpCodegen() { super(); + // C# does not use import mapping + importMapping.clear(); + outputFolder = "generated-code" + File.separator + this.getName(); embeddedTemplateDir = templateDir = this.getName(); @@ -57,6 +60,10 @@ public AbstractCSharpCodegen() { setReservedWordsLowerCase( Arrays.asList( + // set client as a reserved word to avoid conflicts with IO.Swagger.Client + // this is a workaround and can be removed if c# api client is updated to use + // fully qualified name + "client", // local variable names in API methods (endpoints) "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", @@ -459,7 +466,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "\"" + dp.getDefault().toString() + "\""; + return "\"" + dp.getDefault() + "\""; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -608,6 +615,11 @@ public void setSourceFolder(String sourceFolder) { @Override public String toEnumVarName(String name, String datatype) { + // for symbol, e.g. $, # + if (getSymbolName(name) != null) { + return camelize(getSymbolName(name)); + } + String enumName = sanitizeName(name); enumName = enumName.replaceFirst("^_", ""); @@ -665,7 +677,7 @@ public String escapeQuotationMark(String input) { @Override public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); + return input.replace("*/", "*_/").replace("/*", "/_*").replace("--", "- -"); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index c245125f80a..ef87b3e1373 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -1,20 +1,43 @@ package io.swagger.codegen.languages; +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; + import com.google.common.base.Strings; -import io.swagger.codegen.*; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; - -import java.io.File; -import java.util.*; -import java.util.regex.Pattern; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig { @@ -43,6 +66,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public AbstractJavaCodegen() { super(); + supportsInheritance = true; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); apiTestTemplateFiles.put("api_test.mustache", ".java"); @@ -96,7 +120,7 @@ public AbstractJavaCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants .SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); - cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util")); + cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util. This option only works for Java API client")); cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); @@ -117,6 +141,18 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + // guess from api package + String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.API_PACKAGE)); + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + LOGGER.info("Invoker Package Name, originally not set, is now dervied from api package name: " + derviedInvokerPackage); + } else if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + // guess from model package + String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + LOGGER.info("Invoker Package Name, originally not set, is now dervied from model package name: " + derviedInvokerPackage); } else { //not set, use default to be passed to template additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); @@ -209,10 +245,14 @@ public void processOpts() { importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty"); importMapping.put("ApiModel", "io.swagger.annotations.ApiModel"); importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty"); + importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator"); importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName"); importMapping.put("Objects", "java.util.Objects"); importMapping.put("StringUtil", invokerPackage + ".StringUtil"); + // import JsonCreator if JsonProperty is imported + // used later in recursive import in postProcessingModels + importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator"); if(additionalProperties.containsKey(DATE_LIBRARY)) { setDateLibrary(additionalProperties.get("dateLibrary").toString()); @@ -311,7 +351,7 @@ public String toVarName(String name) { name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if ("class".equals(name.toLowerCase())) { - return "PropertyClass"; + return "propertyClass"; } if("_".equals(name)) { @@ -337,6 +377,11 @@ public String toVarName(String name) { @Override public String toParamName(String name) { + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "paramCallback"; + } + // should be the same as variable name return toVarName(name); } @@ -562,7 +607,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe if(codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } - if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { + if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); @@ -603,6 +648,23 @@ public void postProcessParameter(CodegenParameter parameter) { } @Override public Map postProcessModels(Map objs) { + // recursively add import for mapping one type to multiple imports + List> recursiveImports = (List>) objs.get("imports"); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = recursiveImports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + Map newImportMap= new HashMap(); + newImportMap.put("import", importMapping.get(_import)); + listIterator.add(newImportMap); + } + } + return postProcessModelsEnum(objs); } @@ -694,6 +756,11 @@ public String toEnumName(CodegenProperty property) { @Override public String toEnumVarName(String value, String datatype) { + // for symbol, e.g. $, # + if (getSymbolName(value) != null) { + return getSymbolName(value).toUpperCase(); + } + // number if ("Integer".equals(datatype) || "Long".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype)) { @@ -705,7 +772,7 @@ public String toEnumVarName(String value, String datatype) { } // string - String var = value.replaceAll("\\W+", "_").replaceAll("_+", "_").toUpperCase(); + String var = value.replaceAll("\\W+", "_").toUpperCase(); if (var.matches("\\d.*")) { return "_" + var; } else { @@ -845,4 +912,29 @@ public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } + /* + * Derive invoker package name based on the input + * e.g. foo.bar.model => foo.bar + * + * @param input API package/model name + * @return Derived invoker package name based on API package/model name + */ + private String deriveInvokerPackageName(String input) { + String[] parts = input.split(Pattern.quote(".")); // Split on period. + + StringBuilder sb = new StringBuilder(); + String delim = ""; + for (String p : Arrays.copyOf(parts, parts.length-1)) { + sb.append(delim).append(p); + delim = "."; + } + return sb.toString(); + } + + + // TODO: Override DefaultCodeGen - Temporary solution to fix invalid BeanValidation-Regexp-patterns surrounded with "/" + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index d1458514256..9ed96485119 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -33,6 +33,8 @@ public AbstractJavaJAXRSServerCodegen() modelPackage = "io.swagger.model"; additionalProperties.put("title", title); + // java inflector uses the jackson lib + additionalProperties.put("jackson", "true"); cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); cliOptions.add(new CliOption("title", "a title describing the application")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java new file mode 100644 index 00000000000..f0eb365d0c8 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java @@ -0,0 +1,656 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.HashSet; +import java.util.regex.Matcher; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractPhpCodegen extends DefaultCodegen implements CodegenConfig { + + static Logger LOGGER = LoggerFactory.getLogger(AbstractPhpCodegen.class); + + public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention"; + public static final String PACKAGE_PATH = "packagePath"; + public static final String SRC_BASE_PATH = "srcBasePath"; + // composerVendorName/composerProjectName has be replaced by gitUserId/gitRepoId. prepare to remove these. + // public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; + // public static final String COMPOSER_PROJECT_NAME = "composerProjectName"; + // protected String composerVendorName = null; + // protected String composerProjectName = null; + protected String invokerPackage = "php"; + protected String packagePath = "php-base"; + protected String artifactVersion = null; + protected String srcBasePath = "lib"; + protected String testBasePath = "test"; + protected String docsBasePath = "docs"; + protected String apiDirName = "Api"; + protected String modelDirName = "Model"; + protected String variableNamingConvention= "snake_case"; + protected String apiDocPath = docsBasePath + "/" + apiDirName; + protected String modelDocPath = docsBasePath + "/" + modelDirName; + + public AbstractPhpCodegen() { + super(); + + modelTemplateFiles.put("model.mustache", ".php"); + apiTemplateFiles.put("api.mustache", ".php"); + apiTestTemplateFiles.put("api_test.mustache", ".php"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; + + setReservedWordsLowerCase( + Arrays.asList( + // local variables used in api methods (endpoints) + "resourcePath", "httpBody", "queryParams", "headerParams", + "formParams", "_header_accept", "_tempBody", + + // PHP reserved words + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") + ); + + // ref: http://php.net/manual/en/language.types.intro.php + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "boolean", + "int", + "integer", + "double", + "float", + "string", + "object", + "DateTime", + "mixed", + "number", + "void", + "byte") + ); + + instantiationTypes.put("array", "array"); + instantiationTypes.put("map", "map"); + + + // provide primitives to mustache template + String primitives = "'" + StringUtils.join(languageSpecificPrimitives, "', '") + "'"; + additionalProperties.put("primitives", primitives); + + // ref: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types + typeMapping = new HashMap(); + typeMapping.put("integer", "int"); + typeMapping.put("long", "int"); + typeMapping.put("number", "float"); + typeMapping.put("float", "float"); + typeMapping.put("double", "double"); + typeMapping.put("string", "string"); + typeMapping.put("byte", "int"); + typeMapping.put("boolean", "bool"); + typeMapping.put("Date", "\\DateTime"); + typeMapping.put("DateTime", "\\DateTime"); + typeMapping.put("file", "\\SplFileObject"); + typeMapping.put("map", "map"); + typeMapping.put("array", "array"); + typeMapping.put("list", "array"); + typeMapping.put("object", "object"); + typeMapping.put("binary", "string"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("UUID", "string"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(VARIABLE_NAMING_CONVENTION, "naming convention of variable name, e.g. camelCase.") + .defaultValue("snake_case")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets")); + cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); + cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); + // cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release")); + cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC)); + // cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); + cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(PACKAGE_PATH)) { + this.setPackagePath((String) additionalProperties.get(PACKAGE_PATH)); + } else { + additionalProperties.put(PACKAGE_PATH, packagePath); + } + + if (additionalProperties.containsKey(SRC_BASE_PATH)) { + this.setSrcBasePath((String) additionalProperties.get(SRC_BASE_PATH)); + } else { + additionalProperties.put(SRC_BASE_PATH, srcBasePath); + } + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } else { + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + + if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + } + + if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + } + + // if (additionalProperties.containsKey(COMPOSER_PROJECT_NAME)) { + // this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME)); + // } else { + // additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName); + // } + + if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) { + this.setGitUserId((String) additionalProperties.get(CodegenConstants.GIT_USER_ID)); + } else { + additionalProperties.put(CodegenConstants.GIT_USER_ID, gitUserId); + } + + // if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) { + // this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME)); + // } else { + // additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName); + // } + + if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) { + this.setGitRepoId((String) additionalProperties.get(CodegenConstants.GIT_REPO_ID)); + } else { + additionalProperties.put(CodegenConstants.GIT_REPO_ID, gitRepoId); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { + this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + } + + if (additionalProperties.containsKey(VARIABLE_NAMING_CONVENTION)) { + this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION)); + } + + additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); + + // make api and model src path available in mustache template + additionalProperties.put("apiSrcPath", "./" + toSrcPath(apiPackage, srcBasePath)); + additionalProperties.put("modelSrcPath", "./" + toSrcPath(modelPackage, srcBasePath)); + additionalProperties.put("apiTestPath", "./" + testBasePath + "/" + apiDirName); + additionalProperties.put("modelTestPath", "./" + testBasePath + "/" + modelDirName); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + // make test path available in mustache template + additionalProperties.put("testBasePath", testBasePath); + + // // apache v2 license + // supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE")); + } + + public String getPackagePath() { + return packagePath; + } + + public String toPackagePath(String packageName, String basePath) { + return (getPackagePath() + File.separatorChar + toSrcPath(packageName, basePath)); + } + + public String toSrcPath(String packageName, String basePath) { + packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + if (basePath != null && basePath.length() > 0) { + basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + } + + String regFirstPathSeparator; + if ("/".equals(File.separator)) { // for mac, linux + regFirstPathSeparator = "^/"; + } else { // for windows + regFirstPathSeparator = "^\\\\"; + } + + String regLastPathSeparator; + if ("/".equals(File.separator)) { // for mac, linux + regLastPathSeparator = "/$"; + } else { // for windows + regLastPathSeparator = "\\\\$"; + } + + return (basePath + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) + // Trim prefix file separators from package path + .replaceAll(regFirstPathSeparator, "")) + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator+ "$", ""); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/" + toPackagePath(apiPackage, srcBasePath)); + } + + @Override + public String modelFileFolder() { + return (outputFolder + "/" + toPackagePath(modelPackage, srcBasePath)); + } + + @Override + public String apiTestFileFolder() { + return (outputFolder + "/" + getPackagePath() + "/" + testBasePath + "/" + apiDirName); + } + + @Override + public String modelTestFileFolder() { + return (outputFolder + "/" + getPackagePath() + "/" + testBasePath + "/" + modelDirName); + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + getPackagePath() + "/" + apiDocPath); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + getPackagePath() + "/" + modelDocPath); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getTypeDeclaration(inner) + "[]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (p instanceof RefProperty) { + String type = super.getTypeDeclaration(p); + return (!languageSpecificPrimitives.contains(type)) + ? "\\" + modelPackage + "\\" + type : type; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getTypeDeclaration(String name) { + if (!languageSpecificPrimitives.contains(name)) { + return "\\" + modelPackage + "\\" + name; + } + return super.getTypeDeclaration(name); + } + + @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 if (instantiationTypes.containsKey(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } + return toModelName(type); + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public void setPackagePath(String packagePath) { + this.packagePath = packagePath; + } + + public void setSrcBasePath(String srcBasePath) { + this.srcBasePath = srcBasePath; + } + + public void setParameterNamingConvention(String variableNamingConvention) { + this.variableNamingConvention = variableNamingConvention; + } + + // public void setComposerVendorName(String composerVendorName) { + // this.composerVendorName = composerVendorName; + // } + + // public void setComposerProjectName(String composerProjectName) { + // this.composerProjectName = composerProjectName; + // } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + if ("camelCase".equals(variableNamingConvention)) { + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); + } else { // default to snake case + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); + } + + // parameter name starting with number won't compile + // need to escape it by appending _ at the beginning + if (name.matches("^\\d.*")) { + name = "_" + name; + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // remove [ + name = name.replaceAll("\\]", ""); + + // Note: backslash ("\\") is allowed for e.g. "\\DateTime" + name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // remove dollar sign + name = name.replaceAll("$", ""); + + // model name cannot use reserved keyword + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + // add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime) + if (!name.matches("^\\\\.*")) { + name = modelNamePrefix + name + modelNameSuffix; + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String toModelTestFilename(String name) { + // should be the same as the model name + return toModelName(name) + "Test"; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + operationId = "call_" + operationId; + } + + return camelize(sanitizeName(operationId), true); + } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (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 setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Integer".equals(type) || "int".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("\\SplFileObject".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Date".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "new \\DateTime(\"" + escapeText(example) + "\")"; + } else if ("DateTime".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "new \\DateTime(\"" + escapeText(example) + "\")"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = "new " + type + "()"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "array(" + example + ")"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "array('key' => " + example + ")"; + } + + p.example = example; + } + + @Override + public String toEnumValue(String value, String datatype) { + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + return value; + } else { + return "\'" + escapeText(value) + "\'"; + } + } + + @Override + public String toEnumDefaultValue(String value, String datatype) { + return datatype + "_" + value; + } + + @Override + public String toEnumVarName(String name, String datatype) { + // for symbol, e.g. $, # + if (getSymbolName(name) != null) { + return (getSymbolName(name)).toUpperCase(); + } + + // number + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + String varName = name; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // string + String enumName = sanitizeName(underscore(name).toUpperCase()); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return "_" + enumName; + } else { + return enumName; + } + } + + @Override + public String toEnumName(CodegenProperty property) { + String enumName = underscore(toModelName(property.name)).toUpperCase(); + + if (enumName.matches("\\d.*")) { // starts with number + return "_" + enumName; + } else { + return enumName; + } + } + + @Override + public Map postProcessModels(Map objs) { + // process enum in models + return postProcessModelsEnum(objs); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.vendorExtensions.put("x-testOperationId", camelize(op.operationId)); + } + return objs; + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", ""); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java new file mode 100644 index 00000000000..e482fa1dd27 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java @@ -0,0 +1,184 @@ +package io.swagger.codegen.languages; + +import java.io.File; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConstants; +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.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 AbstractScalaCodegen extends DefaultCodegen { + + protected String modelPropertyNaming = "camelCase"; + protected String invokerPackage = "io.swagger.client"; + protected String sourceFolder = "src/main/scala"; + + public AbstractScalaCodegen() { + super(); + + languageSpecificPrimitives.addAll(Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "Any", + "List", + "Seq", + "Map")); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + public String getSourceFolder() { + return sourceFolder; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else { + return null; + } + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "null"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + return "null"; + } else if (p instanceof FloatProperty) { + return "null"; + } else if (p instanceof IntegerProperty) { + return "null"; + } else if (p instanceof LongProperty) { + return "null"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap[String, " + inner + "]() "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ListBuffer[" + inner + "]() "; + } else { + return "null"; + } + } + + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid warnings for importing class in the same package in Scala + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage() + "."; + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) iterator.remove(); + } + return objs; + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + +} \ No newline at end of file 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 2435516f0f6..71f7d32c5eb 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 @@ -3,14 +3,17 @@ import org.apache.commons.lang3.StringUtils; import java.io.File; +import java.util.List; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.TreeSet; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -26,6 +29,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp public AbstractTypeScriptClientCodegen() { super(); + + // clear import mapping (from default generator) as TS does not use it + // at the moment + importMapping.clear(); + supportsInheritance = true; setReservedWordsLowerCase(Arrays.asList( // local variable names used in API methods (endpoints) @@ -252,7 +260,7 @@ public String getNameUsingModelPropertyNaming(String name) { @Override public String toEnumValue(String value, String datatype) { - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + if ("number".equals(datatype)) { return value; } else { return "\'" + escapeText(value) + "\'"; @@ -266,9 +274,15 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { + // for symbol, e.g. $, # + if (getSymbolName(name) != null) { + return camelize(getSymbolName(name)); + } + // number - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = new String(name); + if ("number".equals(datatype)) { + String varName = "NUMBER_" + name; + varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); @@ -276,10 +290,14 @@ public String toEnumVarName(String name, String datatype) { } // string - String enumName = sanitizeName(underscore(name).toUpperCase()); + String enumName = sanitizeName(name); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); + // camelize the enum variable name + // ref: https://basarat.gitbooks.io/typescript/content/docs/enums.html + enumName = camelize(enumName); + if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { @@ -301,7 +319,20 @@ public String toEnumName(CodegenProperty property) { @Override public Map postProcessModels(Map objs) { // process enum in models - return postProcessModelsEnum(objs); + List models = (List) postProcessModelsEnum(objs).get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + cm.imports = new TreeSet(cm.imports); + for (CodegenProperty var : cm.vars) { + // name enum with model name, e.g. StatuEnum => Pet.StatusEnum + if (Boolean.TRUE.equals(var.isEnum)) { + var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + "." + var.enumName); + } + } + } + + return objs; } public void setSupportsES6(Boolean value) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index 4b7c321e802..8be1c1f6d50 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -12,7 +12,6 @@ import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenSecurity; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.properties.ArrayProperty; @@ -42,13 +41,11 @@ import java.util.List; import java.util.Map; -public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig { +public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String mainPackage = "io.swagger.client"; - protected String invokerPackage = mainPackage + ".core"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; protected String resourcesFolder = "src/main/resources"; protected String configKey = "apiRequest"; protected int defaultTimeoutInMs = 5000; @@ -75,6 +72,7 @@ public AkkaScalaClientCodegen() { embeddedTemplateDir = templateDir = "akka-scala"; apiPackage = mainPackage + ".api"; modelPackage = mainPackage + ".model"; + invokerPackage = mainPackage + ".core"; setReservedWordsLowerCase( Arrays.asList( @@ -135,25 +133,8 @@ public AkkaScalaClientCodegen() { typeMapping.put("file", "File"); typeMapping.put("number", "Double"); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Seq", - "Map") - ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "Map"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -176,16 +157,6 @@ public String escapeReservedWord(String name) { return "`" + name + "`"; } - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - @Override public Map postProcessOperations(Map objs) { if (registerNonStandardStatusCodes) { @@ -218,21 +189,6 @@ public Map postProcessOperations(Map objs) { return super.postProcessOperations(objs); } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } - @Override public List fromSecurity(Map schemes) { final List codegenSecurities = super.fromSecurity(schemes); @@ -297,36 +253,6 @@ public String toEnumName(CodegenProperty property) { return formatIdentifier(property.baseName, true); } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else { - return null; - } - } - @Override public String toDefaultValue(Property p) { if (!p.getRequired()) { @@ -419,9 +345,4 @@ public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 788223bec9b..e4dacc499bb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -29,6 +29,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi protected String projectFolder = "src/main"; protected String sourceFolder = projectFolder + "/java"; protected Boolean useAndroidMavenGradlePlugin = true; + protected Boolean serializableModel = false; // requestPackage and authPackage are used by the "volley" template/library protected String requestPackage = "io.swagger.client.request"; @@ -90,6 +91,8 @@ public AndroidClientCodegen() { cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)"); supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); @@ -378,6 +381,14 @@ public void processOpts() { this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); } + if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { + this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + } + + // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string + additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); + LOGGER.info("CodegenConstants.SERIALIZABLE_MODEL = " + additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL)); + //make api and model doc path available in mustache template additionalProperties.put( "apiDocPath", apiDocPath ); additionalProperties.put( "modelDocPath", modelDocPath ); @@ -504,6 +515,10 @@ public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } + public void setSerializableModel(Boolean serializableModel) { + this.serializableModel = serializableModel; + } + @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java index 099d049707b..e98c1441254 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java @@ -9,10 +9,14 @@ import java.io.File; import java.util.*; +import static java.util.UUID.randomUUID; + public class AspNet5ServerCodegen extends AbstractCSharpCodegen { protected String sourceFolder = "src" + File.separator + packageName; + private final String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}"; + @SuppressWarnings("hiding") protected Logger LOGGER = LoggerFactory.getLogger(AspNet5ServerCodegen.class); @@ -81,17 +85,27 @@ public String getHelp() { public void processOpts() { super.processOpts(); + additionalProperties.put("packageGuid", packageGuid); + apiPackage = packageName + ".Controllers"; modelPackage = packageName + ".Models"; + supportingFiles.add(new SupportingFile("NuGet.Config", "", "NuGet.Config")); supportingFiles.add(new SupportingFile("global.json", "", "global.json")); - supportingFiles.add(new SupportingFile("build.mustache", "", "build.sh")); + supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); + supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln")); supportingFiles.add(new SupportingFile("Dockerfile.mustache", this.sourceFolder, "Dockerfile")); supportingFiles.add(new SupportingFile("gitignore", this.sourceFolder, ".gitignore")); supportingFiles.add(new SupportingFile("appsettings.json", this.sourceFolder, "appsettings.json")); - supportingFiles.add(new SupportingFile("project.mustache", this.sourceFolder, "project.json")); + supportingFiles.add(new SupportingFile("project.json.mustache", this.sourceFolder, "project.json")); supportingFiles.add(new SupportingFile("Startup.mustache", this.sourceFolder, "Startup.cs")); + supportingFiles.add(new SupportingFile("Program.mustache", this.sourceFolder, "Program.cs")); + supportingFiles.add(new SupportingFile("web.config", this.sourceFolder, "web.config")); + + supportingFiles.add(new SupportingFile("Project.xproj.mustache", this.sourceFolder, this.packageName + ".xproj")); supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 17fd4ab57b6..ea8ae308081 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -4,31 +4,16 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; import java.io.File; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; -public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; +public class AsyncScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String groupId = "io.swagger"; protected String artifactId = "swagger-async-scala-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; protected String clientName = "SwaggerClient"; protected String authScheme = ""; protected boolean authPreemptive; @@ -94,24 +79,8 @@ public AsyncScalaClientCodegen() { typeMapping.put("object", "Any"); typeMapping.put("file", "File"); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Map") - ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -128,95 +97,4 @@ public String getName() { public String getHelp() { return "Generates an Asynchronous Scala client library."; } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else { - return null; - } - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "null"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - return "null"; - } else if (p instanceof FloatProperty) { - return "null"; - } else if (p instanceof IntegerProperty) { - return "null"; - } else if (p instanceof LongProperty) { - return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap[String, " + inner + "]() "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; - } else { - return "null"; - } - } } 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 708ffda2c43..f1b43088b23 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 @@ -1,32 +1,23 @@ package io.swagger.codegen.languages; -import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; -import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.SupportingFile; import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenParameter; -import io.swagger.models.properties.*; import io.swagger.codegen.CliOption; import io.swagger.models.Model; import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; +import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.text.WordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,8 +39,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { protected String targetFrameworkNuget = "net45"; protected boolean supportsAsync = Boolean.TRUE; protected boolean supportsUWP = Boolean.FALSE; - - + protected boolean generatePropertyChanged = Boolean.FALSE; + protected Map regexModifiers; protected final Map frameworks; public CSharpClientCodegen() { @@ -96,6 +87,10 @@ public CSharpClientCodegen() { cliOptions.add(framework); // CLI Switches + addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, + this.hideGenerationTimestamp); + addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, this.sortParamsByRequiredFlag); @@ -127,13 +122,31 @@ public CSharpClientCodegen() { addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, this.optionalEmitDefaultValue); + + addSwitch(CodegenConstants.GENERATE_PROPERTY_CHANGED, + CodegenConstants.PACKAGE_DESCRIPTION_DESC, + this.generatePropertyChanged); + + regexModifiers = new HashMap(); + regexModifiers.put('i', "IgnoreCase"); + regexModifiers.put('m', "Multiline"); + regexModifiers.put('s', "Singleline"); + regexModifiers.put('x', "IgnorePatternWhitespace"); } @Override public void processOpts() { super.processOpts(); - Boolean excludeTests = false; + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + Boolean excludeTests = false; if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); } @@ -173,6 +186,14 @@ public void processOpts() { additionalProperties.put("supportsAsync", this.supportsAsync); } + if(additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { + if(NET35.equals(targetFramework)) { + LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is only supported by generated code for .NET 4+."); + } else { + setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get(CodegenConstants.GENERATE_PROPERTY_CHANGED).toString())); + } + } + additionalProperties.put("targetFrameworkNuget", this.targetFrameworkNuget); if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE)) { @@ -239,6 +260,10 @@ public void processOpts() { supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); } + if(Boolean.TRUE.equals(generatePropertyChanged)) { + supportingFiles.add(new SupportingFile("FodyWeavers.xml", packageFolder, "FodyWeavers.xml")); + } + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); @@ -333,6 +358,56 @@ public Map postProcessModels(Map objMap) { return super.postProcessModels(objMap); } + @Override + public void postProcessParameter(CodegenParameter parameter) { + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + super.postProcessParameter(parameter); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + super.postProcessModelProperty(model, property); + } + + + /* + * The swagger pattern spec follows the Perl convention and style of modifiers. .NET + * does not support this syntax directly so we need to convert the pattern to a .NET compatible + * format and apply modifiers in a compatible way. + * See https://msdn.microsoft.com/en-us/library/yd1hzczs(v=vs.110).aspx for .NET options. + * See https://github.com/swagger-api/swagger-codegen/pull/2794 for Python's initial implementation from which this is copied. + */ + public void postProcessPattern(String pattern, Map vendorExtensions) { + if(pattern != null) { + int i = pattern.lastIndexOf('/'); + + //Must follow Perl /pattern/modifiers convention + if(pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. "+pattern+" is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\'"); + List modifiers = new ArrayList(); + + // perl requires an explicit modifier to be culture specific and .NET is the reverse. + modifiers.add("CultureInvariant"); + + for(char c : pattern.substring(i).toCharArray()) { + if(regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } else if (c == 'l') { + modifiers.remove("CultureInvariant"); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } + public void setTargetFramework(String dotnetFramework) { if(!frameworks.containsKey(dotnetFramework)){ LOGGER.warn("Invalid .NET framework version, defaulting to " + this.targetFramework); @@ -402,6 +477,11 @@ public String toEnumValue(String value, String datatype) { @Override public String toEnumVarName(String value, String datatype) { + // for symbol, e.g. $, # + if (getSymbolName(value) != null) { + return camelize(getSymbolName(value)); + } + // number if ("int?".equals(datatype) || "long?".equals(datatype) || "double?".equals(datatype) || "float?".equals(datatype)) { @@ -414,10 +494,10 @@ public String toEnumVarName(String value, String datatype) { // string String var = value.replaceAll("_", " "); - var = WordUtils.capitalizeFully(var); + //var = WordUtils.capitalizeFully(var); + var = camelize(var); var = var.replaceAll("\\W+", ""); - if (var.matches("\\d.*")) { return "_" + var; } else { @@ -446,6 +526,10 @@ public void setSupportsUWP(Boolean supportsUWP){ this.supportsUWP = supportsUWP; } + public void setGeneratePropertyChanged(final Boolean generatePropertyChanged){ + this.generatePropertyChanged = generatePropertyChanged; + } + @Override public String toModelDocFilename(String name) { return toModelFilename(name); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java new file mode 100644 index 00000000000..972721bcfa1 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java @@ -0,0 +1,107 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class ConfluenceWikiGenerator extends DefaultCodegen implements CodegenConfig { + private static final String ALL_OPERATIONS = ""; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public ConfluenceWikiGenerator() { + super(); + outputFolder = "docs"; + embeddedTemplateDir = templateDir = "confluenceWikiDocs"; + + defaultIncludes = new HashSet(); + + cliOptions.add(new CliOption("appName", "short name of the application")); + cliOptions.add(new CliOption("appDescription", "description of the application")); + cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); + cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); + + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "https://helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + supportingFiles.add(new SupportingFile("index.mustache", "", "confluence-markup.txt")); + reservedWords = new HashSet(); + + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap(); + } + + @Override + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + @Override + public String getName() { + return "cwiki"; + } + + @Override + public String getHelp() { + return "Generates confluence wiki markup."; + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } +} 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 c6715b22fb2..4c7cc7c1f0b 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 @@ -217,6 +217,10 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation if (methodResponse.getSchema() != null) { CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); op.vendorExtensions.put("x-codegen-response", cm); + if(cm.datatype == "HttpContent") + { + op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); + } } } } @@ -267,7 +271,8 @@ public String getTypeDeclaration(Property p) { Property inner = mp.getAdditionalProperties(); return getSwaggerType(p) + ""; } - if (p instanceof StringProperty || p instanceof DateProperty || p instanceof DateTimeProperty + if (p instanceof StringProperty || p instanceof DateProperty + || p instanceof DateTimeProperty || p instanceof FileProperty || languageSpecificPrimitives.contains(swaggerType)) { return toModelName(swaggerType); } @@ -289,7 +294,7 @@ public String toDefaultValue(Property p) { return "0.0"; } else if (p instanceof FloatProperty) { return "0.0f"; - } else if (p instanceof IntegerProperty) { + } else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) { return "0"; } else if (p instanceof LongProperty) { return "0L"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index d13c6c851da..0750a667b3a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -24,6 +24,11 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege public CsharpDotNet2ClientCodegen() { super(); + + // clear import mapping (from default generator) as C# (2.0) does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code" + File.separator + "CsharpDotNet2"; modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 6bb54cb9d50..652ff759deb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -28,6 +28,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public DartClientCodegen() { super(); + + // clear import mapping (from default generator) as dart does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code/dart"; modelTemplateFiles.put("model.mustache", ".dart"); apiTemplateFiles.put("api.mustache", ".dart"); @@ -53,6 +58,7 @@ public DartClientCodegen() { "String", "bool", "int", + "num", "double") ); instantiationTypes.put("array", "List"); @@ -64,11 +70,12 @@ public DartClientCodegen() { typeMapping.put("List", "List"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "String"); + typeMapping.put("char", "String"); typeMapping.put("int", "int"); - typeMapping.put("float", "double"); typeMapping.put("long", "int"); typeMapping.put("short", "int"); - typeMapping.put("char", "String"); + typeMapping.put("number", "num"); + typeMapping.put("float", "double"); typeMapping.put("double", "double"); typeMapping.put("object", "Object"); typeMapping.put("integer", "int"); @@ -140,8 +147,10 @@ public void processOpts() { final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); + supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options")); supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); - supportingFiles.add(new SupportingFile("apiException.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart")); final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java new file mode 100644 index 00000000000..65162cdd228 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java @@ -0,0 +1,280 @@ +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.util.Json; +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 ErlangServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(ErlangServerCodegen.class); + + protected String apiVersion = "1.0.0"; + protected String apiPath = "src"; + protected String packageName = "swagger"; + + public ErlangServerCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/erlang-server"; + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + }; + + /** + * 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.put( + "handler.mustache", // the template to use + ".erl"); // the extension for each file to write + + /** + * 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 = "erlang-server"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + 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", "date"); + typeMapping.put("datetime", "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", "map"); + typeMapping.put("number", "integer"); + typeMapping.put("bigdecimal", "float"); + typeMapping.put("List", "list"); + typeMapping.put("object", "object"); + typeMapping.put("file", "file"); + 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 package name (convention: lowercase).") + .defaultValue(this.packageName)); + /** + * 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("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("rebar.config.mustache","", "rebar.config")); + supportingFiles.add(new SupportingFile("app.src.mustache", "", "src" + File.separator + this.packageName + ".app.src")); + supportingFiles.add(new SupportingFile("router.mustache", "", toSourceFilePath("router", "erl"))); + supportingFiles.add(new SupportingFile("api.mustache", "", toSourceFilePath("api", "erl"))); + supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl"))); + supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl"))); + supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); + supportingFiles.add(new SupportingFile("swagger.mustache", "", toPrivFilePath("swagger", "json"))); + supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl"))); + supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl"))); + writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); + } + + @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 "erlang-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 an Erlang server library (beta) using the Swagger Codegen project. By default, " + + "it will also generate service classes, which can be disabled with the `-Dnoservice` environment variable."; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return this.packageName + "_default_handler"; + } + return this.packageName + "_" + underscore(name) + "_handler"; + } + + /** + * 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) { + 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) { + return camelize(toModelFilename(name)); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return camelize(operationId); + } + + @Override + public String toApiFilename(String name) { + return toHandlerName(name); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + if (op.path != null) { + op.path = op.path.replaceAll("\\{(.*?)\\}", ":$1"); + } + } + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + return super.postProcessSupportingFileData(objs); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + protected String toHandlerName(String name) { + return toModuleName(name) + "_handler"; + } + + protected String toModuleName(String name) { + return this.packageName + "_" + underscore(name.replaceAll("-", "_")); + } + + protected String toSourceFilePath(String name, String extension) { + return "src" + File.separator + toModuleName(name) + "." + extension; + } + + protected String toIncludeFilePath(String name, String extension) { + return "include" + File.separator + toModuleName(name) + "." + extension; + } + + protected String toPrivFilePath(String name, String extension) { + return "priv" + File.separator + name + "." + extension; + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + // ref: http://stackoverflow.com/a/30421295/677735 + return input.replace("-ifdef", "- if def").replace("-endif", "- end if"); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index 2d00c8cf7a2..aa0318a9ab5 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -1,387 +1,387 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang3.StringUtils; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; - -public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String packageName = "io.swagger"; - protected String packageVersion; - - protected String invokerPackage = "io.swagger"; - protected String sourceFolder = "flash"; - - public FlashClientCodegen() { - super(); - - modelPackage = "io.swagger.client.model"; - apiPackage = "io.swagger.client.api"; - outputFolder = "generated-code" + File.separatorChar + "flash"; - modelTemplateFiles.put("model.mustache", ".as"); - modelTemplateFiles.put("modelList.mustache", "List.as"); - apiTemplateFiles.put("api.mustache", ".as"); - embeddedTemplateDir = templateDir = "flash"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("Number"); - languageSpecificPrimitives.add("Boolean"); - languageSpecificPrimitives.add("String"); - languageSpecificPrimitives.add("Date"); - languageSpecificPrimitives.add("Array"); - languageSpecificPrimitives.add("Dictionary"); - - typeMapping.clear(); - typeMapping.put("integer", "Number"); - typeMapping.put("float", "Number"); - typeMapping.put("long", "Number"); - typeMapping.put("double", "Number"); - typeMapping.put("array", "Array"); - typeMapping.put("map", "Dictionary"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("date", "Date"); - typeMapping.put("DateTime", "Date"); - typeMapping.put("object", "Object"); - typeMapping.put("file", "File"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "String"); - - importMapping = new HashMap(); - importMapping.put("File", "flash.filesystem.File"); - - // from - setReservedWordsLowerCase(Arrays.asList("add", "for", "lt", "tellTarget", "and", - "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", - "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", - "else", "in", "or", "with", "eq", "le", "return")); - - cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + - " package.name)").defaultValue("io.swagger")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated " + - "code. e.g. flash")); - - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - } else { - //not set, use default to be passed to template - additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); - } - - if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { - this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - apiPackage = packageName + ".client.api"; - modelPackage = packageName + ".client.model"; - } - else { - setPackageName("io.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); - - //modelPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "model"; - //apiPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "api"; - - final String invokerFolder = (sourceFolder + File.separator + "src/" + invokerPackage + File.separator).replace(".", File.separator).replace('.', File.separatorChar); - - supportingFiles.add(new SupportingFile("ApiInvoker.as", invokerFolder + "common", "ApiInvoker.as")); - supportingFiles.add(new SupportingFile("ApiUrlHelper.as", invokerFolder + "common", "ApiUrlHelper.as")); - supportingFiles.add(new SupportingFile("ApiUserCredentials.as", invokerFolder + "common", "ApiUserCredentials.as")); - supportingFiles.add(new SupportingFile("ListWrapper.as", invokerFolder + "common", "ListWrapper.as")); - supportingFiles.add(new SupportingFile("SwaggerApi.as", invokerFolder + "common", "SwaggerApi.as")); - supportingFiles.add(new SupportingFile("XMLWriter.as", invokerFolder + "common", "XMLWriter.as")); - supportingFiles.add(new SupportingFile("ApiError.as", invokerFolder + "exception", "ApiError.as")); - supportingFiles.add(new SupportingFile("ApiErrorCodes.as", invokerFolder + "exception", "ApiErrorCodes.as")); - supportingFiles.add(new SupportingFile("ApiClientEvent.as", invokerFolder + "event", "ApiClientEvent.as")); - supportingFiles.add(new SupportingFile("Response.as", invokerFolder + "event", "Response.as")); - supportingFiles.add(new SupportingFile("build.properties", sourceFolder, "build.properties")); - supportingFiles.add(new SupportingFile("build.xml", sourceFolder, "build.xml")); - supportingFiles.add(new SupportingFile("README.txt", sourceFolder, "README.txt")); - //supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + File.separatorChar - // + "bin", "AirExecutorApp-app.xml")); - supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar - + "lib", "ASAXB-0.1.1.swc")); - supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar - + "lib", "as3corelib.swc")); - supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - } - - private static String dropDots(String str) { - return str.replaceAll("\\.", "_"); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "flash"; - } - - @Override - public String getHelp() { - return "Generates a Flash client library."; - } - - @Override - public String escapeReservedWord(String name) { - return name + "_"; - } - - @Override - public String apiFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" - + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" - + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty || p instanceof MapProperty) { - return getSwaggerType(p); - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - type = toModelName(swaggerType); - } - return type; - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "false"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0.0"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0.0"; - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0"; - } else if (p instanceof MapProperty) { - return "new Dictionary()"; - } else if (p instanceof ArrayProperty) { - return "new Array()"; - } else { - return "NaN"; - } - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) { - name = name.toLowerCase(); - } - - // underscore the variable name - // petId => pet_id - name = camelize(dropDots(name), true); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(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) - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // leverage toModelName - return dropDots(toModelName(name)); - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return camelize(name) + "Api"; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } - - @Override - public String toApiVarName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - return camelize(name) + "Api"; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // 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); - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public void setPackageVersion(String packageVersion) { - this.packageVersion = packageVersion; - } - - public void setInvokerPackage(String invokerPackage) { - this.invokerPackage = invokerPackage; - } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } -} +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; + +public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String packageName = "io.swagger"; + protected String packageVersion; + + protected String invokerPackage = "io.swagger"; + protected String sourceFolder = "flash"; + + public FlashClientCodegen() { + super(); + + modelPackage = "io.swagger.client.model"; + apiPackage = "io.swagger.client.api"; + outputFolder = "generated-code" + File.separatorChar + "flash"; + modelTemplateFiles.put("model.mustache", ".as"); + modelTemplateFiles.put("modelList.mustache", "List.as"); + apiTemplateFiles.put("api.mustache", ".as"); + embeddedTemplateDir = templateDir = "flash"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("Number"); + languageSpecificPrimitives.add("Boolean"); + languageSpecificPrimitives.add("String"); + languageSpecificPrimitives.add("Date"); + languageSpecificPrimitives.add("Array"); + languageSpecificPrimitives.add("Dictionary"); + + typeMapping.clear(); + typeMapping.put("integer", "Number"); + typeMapping.put("float", "Number"); + typeMapping.put("long", "Number"); + typeMapping.put("double", "Number"); + typeMapping.put("array", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("date", "Date"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("object", "Object"); + typeMapping.put("file", "File"); + //TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "String"); + + importMapping = new HashMap(); + importMapping.put("File", "flash.filesystem.File"); + + // from + setReservedWordsLowerCase(Arrays.asList("add", "for", "lt", "tellTarget", "and", + "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", + "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", + "else", "in", "or", "with", "eq", "le", "return")); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + + " package.name)").defaultValue("io.swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated " + + "code. e.g. flash")); + + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } else { + //not set, use default to be passed to template + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + apiPackage = packageName + ".client.api"; + modelPackage = packageName + ".client.model"; + } + else { + setPackageName("io.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); + + //modelPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "model"; + //apiPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "api"; + + final String invokerFolder = (sourceFolder + File.separator + "src/" + invokerPackage + File.separator).replace(".", File.separator).replace('.', File.separatorChar); + + supportingFiles.add(new SupportingFile("ApiInvoker.as", invokerFolder + "common", "ApiInvoker.as")); + supportingFiles.add(new SupportingFile("ApiUrlHelper.as", invokerFolder + "common", "ApiUrlHelper.as")); + supportingFiles.add(new SupportingFile("ApiUserCredentials.as", invokerFolder + "common", "ApiUserCredentials.as")); + supportingFiles.add(new SupportingFile("ListWrapper.as", invokerFolder + "common", "ListWrapper.as")); + supportingFiles.add(new SupportingFile("SwaggerApi.as", invokerFolder + "common", "SwaggerApi.as")); + supportingFiles.add(new SupportingFile("XMLWriter.as", invokerFolder + "common", "XMLWriter.as")); + supportingFiles.add(new SupportingFile("ApiError.as", invokerFolder + "exception", "ApiError.as")); + supportingFiles.add(new SupportingFile("ApiErrorCodes.as", invokerFolder + "exception", "ApiErrorCodes.as")); + supportingFiles.add(new SupportingFile("ApiClientEvent.as", invokerFolder + "event", "ApiClientEvent.as")); + supportingFiles.add(new SupportingFile("Response.as", invokerFolder + "event", "Response.as")); + supportingFiles.add(new SupportingFile("build.properties", sourceFolder, "build.properties")); + supportingFiles.add(new SupportingFile("build.xml", sourceFolder, "build.xml")); + supportingFiles.add(new SupportingFile("README.txt", sourceFolder, "README.txt")); + //supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + File.separatorChar + // + "bin", "AirExecutorApp-app.xml")); + supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar + + "lib", "ASAXB-0.1.1.swc")); + supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar + + "lib", "as3corelib.swc")); + supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "flash"; + } + + @Override + public String getHelp() { + return "Generates a Flash client library."; + } + + @Override + public String escapeReservedWord(String name) { + return name + "_"; + } + + @Override + public String apiFileFolder() { + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" + + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" + + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty || p instanceof MapProperty) { + return getSwaggerType(p); + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } + return type; + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "false"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0.0"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0.0"; + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0"; + } else if (p instanceof MapProperty) { + return "new Dictionary()"; + } else if (p instanceof ArrayProperty) { + return "new Array()"; + } else { + return "NaN"; + } + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // underscore the variable name + // petId => pet_id + name = camelize(dropDots(name), true); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(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) + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // leverage toModelName + return dropDots(toModelName(name)); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return camelize(name) + "Api"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toApiVarName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + return camelize(name) + "Api"; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // 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); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 153d85f1596..2ac51c7e9e1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -65,9 +65,9 @@ public FlaskConnexionCodegen() { modelTemplateFiles.clear(); - apiTemplateFiles.clear(); + apiTemplateFiles.put("controller.mustache", ".py"); - /** + /* * 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. */ @@ -81,14 +81,14 @@ public FlaskConnexionCodegen() { "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try")); - /** + /* * 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); - /** + /* * 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 @@ -122,7 +122,7 @@ public FlaskConnexionCodegen() { @Override public void processOpts() { super.processOpts(); - apiTemplateFiles.clear(); + //apiTemplateFiles.clear(); if (additionalProperties.containsKey(CONTROLLER_PACKAGE)) { this.controllerPackage = additionalProperties.get(CONTROLLER_PACKAGE).toString(); @@ -145,10 +145,6 @@ public void processOpts() { } if(!new java.io.File(controllerPackage + File.separator + defaultController + ".py").exists()) { - supportingFiles.add(new SupportingFile("controller.mustache", - controllerPackage, - defaultController + ".py") - ); supportingFiles.add(new SupportingFile("__init__.mustache", controllerPackage, "__init__.py") @@ -197,15 +193,15 @@ public String getHelp() { @Override public String toApiName(String name) { - if (name.length() == 0) { + if (name == null || name.length() == 0) { return "DefaultController"; } - return initialCaps(name); + return camelize(name, false) + "Controller"; } @Override public String toApiFilename(String name) { - return toApiName(name); + return underscore(toApiName(name)); } /** @@ -228,24 +224,22 @@ public String apiFileFolder() { return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } + @Override public void preprocessSwagger(Swagger swagger) { - if(swagger != null && swagger.getPaths() != null) { + if (swagger != null && swagger.getPaths() != null) { for(String pathname : swagger.getPaths().keySet()) { Path path = swagger.getPath(pathname); - if(path.getOperations() != null) { + if (path.getOperations() != null) { for(Map.Entry entry : path.getOperationMap().entrySet()) { // Normalize `operationId` and add package/class path in front, e.g. // controllers.default_controller.add_pet String httpMethod = entry.getKey().name().toLowerCase(); Operation operation = entry.getValue(); String operationId = getOrGenerateOperationId(operation, pathname, httpMethod); - if(!operationId.contains(".")) { - operationId = underscore(sanitizeName(operationId)); - operationId = controllerPackage + "." + defaultController + "." + operationId; - } - operation.setOperationId(operationId); - if(operation.getTags() != null) { + String controllerName; + + if (operation.getTags() != null) { List> tags = new ArrayList>(); for(String tag : operation.getTags()) { Map value = new HashMap(); @@ -253,19 +247,32 @@ public void preprocessSwagger(Swagger swagger) { value.put("hasMore", "true"); tags.add(value); } - if(tags.size() > 0) { + + if (tags.size() > 0) { tags.get(tags.size() - 1).remove("hasMore"); } - if(operation.getTags().size() > 0) { + + // use only the first tag + if (operation.getTags().size() > 0) { String tag = operation.getTags().get(0); operation.setTags(Arrays.asList(tag)); + controllerName = tag + "_controller"; + } else { + controllerName = "default_controller"; } + operation.setVendorExtension("x-tags", tags); } else { - String tag = "default_controller"; + // no tag found, use "default_controller" as the default + String tag = "default"; operation.setTags(Arrays.asList(tag)); + controllerName = tag + "_controller"; } + + operationId = underscore(sanitizeName(operationId)); + operationId = controllerPackage + "." + controllerName + "." + operationId; + operation.setOperationId(operationId); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 09672f6b6f6..9681f435534 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -47,6 +47,11 @@ public GoClientCodegen() { setReservedWordsLowerCase( Arrays.asList( + // data type + "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", + "int", "int8", "int16", "int32", "int64", "float32", "float64", + "complex64", "complex128", "rune", "byte", "uintptr", + "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct", "chan", "else", "goto", "package", "switch", @@ -91,6 +96,7 @@ public GoClientCodegen() { typeMapping.put("double", "float64"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "string"); + typeMapping.put("UUID", "string"); typeMapping.put("date", "time.Time"); typeMapping.put("DateTime", "time.Time"); typeMapping.put("password", "string"); @@ -100,6 +106,7 @@ public GoClientCodegen() { // the correct solution is to use []byte typeMapping.put("binary", "string"); typeMapping.put("ByteArray", "string"); + typeMapping.put("object", "interface{}"); importMapping = new HashMap(); importMapping.put("time.Time", "time"); @@ -111,11 +118,22 @@ public GoClientCodegen() { .defaultValue("swagger")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.") .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } @Override public void processOpts() { - //super.processOpts(); + super.processOpts(); + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); @@ -147,7 +165,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go")); supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go")); supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); } @@ -182,7 +199,7 @@ public String modelFileFolder() { @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = sanitizeName(name.replaceAll("-", "_")); // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) @@ -193,9 +210,13 @@ public String toVarName(String name) { name = camelize(name); // for reserved word or word starting with number, append _ - if(isReservedWord(name) || name.matches("^\\d.*")) + if (isReservedWord(name)) name = escapeReservedWord(name); + // for reserved word or word starting with number, append _ + if (name.matches("^\\d.*")) + name = "Var" + name; + return name; } @@ -231,10 +252,16 @@ public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + return underscore(name); } @@ -346,13 +373,15 @@ public String getSwaggerType(Property p) { @Override public String toOperationId(String operationId) { + String sanitizedOperationId = sanitizeName(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; + if (isReservedWord(sanitizedOperationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize("call_" + operationId)); + sanitizedOperationId = "call_" + sanitizedOperationId; } - return camelize(operationId); + return camelize(sanitizedOperationId); } @Override @@ -380,14 +409,21 @@ public Map postProcessOperations(Map objs) { // if the return type is not primitive, import encoding/json for (CodegenOperation operation : operations) { if(operation.returnBaseType != null && needToImport(operation.returnBaseType)) { - Map customImport = new HashMap(); - customImport.put("import", "encoding/json"); - imports.add(customImport); + imports.add(createMapping("import", "encoding/json")); break; //just need to import once } } - // recursivly add import for mapping one type to multipe imports + // this will only import "fmt" if there are items in pathParams + for (CodegenOperation operation : operations) { + if(operation.pathParams != null && operation.pathParams.size() > 0) { + imports.add(createMapping("import", "fmt")); + break; //just need to import once + } + } + + + // recursively add import for mapping one type to multiple imports List> recursiveImports = (List>) objs.get("imports"); if (recursiveImports == null) return objs; @@ -398,9 +434,7 @@ public Map postProcessOperations(Map objs) { // if the import package happens to be found in the importMapping (key) // add the corresponding import package to the list if (importMapping.containsKey(_import)) { - Map newImportMap= new HashMap(); - newImportMap.put("import", importMapping.get(_import)); - listIterator.add(newImportMap); + listIterator.add(createMapping("import", importMapping.get(_import))); } } @@ -419,7 +453,7 @@ public Map postProcessModels(Map objs) { iterator.remove(); } - // recursivly add import for mapping one type to multipe imports + // recursively add import for mapping one type to multiple imports List> recursiveImports = (List>) objs.get("imports"); if (recursiveImports == null) return objs; @@ -430,9 +464,7 @@ public Map postProcessModels(Map objs) { // if the import package happens to be found in the importMapping (key) // add the corresponding import package to the list if (importMapping.containsKey(_import)) { - Map newImportMap= new HashMap(); - newImportMap.put("import", importMapping.get(_import)); - listIterator.add(newImportMap); + listIterator.add(createMapping("import", importMapping.get(_import))); } } @@ -463,4 +495,11 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } + + public Map createMapping(String key, String value){ + Map customImport = new HashMap(); + customImport.put(key, value); + + return customImport; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index b8ce2247652..39c544fba42 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -36,7 +36,7 @@ public GoServerCodegen() { // set the output folder here outputFolder = "generated-code/go"; - /** + /* * 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 @@ -44,7 +44,7 @@ public GoServerCodegen() { */ 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 @@ -53,13 +53,13 @@ public GoServerCodegen() { "controller.mustache", // the template to use ".go"); // the extension for each file to write - /** + /* * 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 = "go-server"; - /** + /* * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( @@ -126,14 +126,14 @@ public GoServerCodegen() { cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") .defaultValue("swagger")); - /** + /* * 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 diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java index 84874b4060f..033dceeb669 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java @@ -12,6 +12,10 @@ public class GroovyClientCodegen extends AbstractJavaCodegen { public GroovyClientCodegen() { super(); + // clear import mapping (from default generator) as groovy does not use it + // at the moment + importMapping.clear(); + sourceFolder = projectFolder + File.separator + "groovy"; outputFolder = "generated-code/groovy"; modelTemplateFiles.put("model.mustache", ".groovy"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index 59d9658ab75..da6642ddef9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -49,8 +49,10 @@ public String getHelp() { public HaskellServantCodegen() { super(); - // override the mapping for "-" (Minus) to keep the original mapping in Haskell - specialCharReplacements.put('-', "Dash"); + // override the mapping to keep the original mapping in Haskell + specialCharReplacements.put("-", "Dash"); + specialCharReplacements.put(">", "GreaterThan"); + specialCharReplacements.put("<", "LessThan"); // set the output folder here outputFolder = "generated-code/haskell-servant"; @@ -203,9 +205,9 @@ public void preprocessSwagger(Swagger swagger) { List> replacements = new ArrayList<>(); Object[] replacementChars = specialCharReplacements.keySet().toArray(); for(int i = 0; i < replacementChars.length; i++) { - Character c = (Character) replacementChars[i]; + String c = (String) replacementChars[i]; Map o = new HashMap<>(); - o.put("char", Character.toString(c)); + o.put("char", c); o.put("replacement", "'" + specialCharReplacements.get(c)); o.put("hasMore", i != replacementChars.length - 1); replacements.add(o); @@ -471,6 +473,11 @@ public CodegenModel fromModel(String name, Model mod, Map allDefi // Create newtypes for things with non-object types String dataOrNewtype = "data"; + // check if it's a ModelImpl before casting + if (!(mod instanceof ModelImpl)) { + return model; + } + String modelType = ((ModelImpl) mod).getType(); if(modelType != "object" && typeMapping.containsKey(modelType)) { String newtype = typeMapping.get(modelType); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 394e7122a04..89893176493 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -53,7 +53,7 @@ public JMeterCodegen() { // set the output folder here outputFolder = "generated-code/JMeterCodegen"; - /** + /* * Api classes. You can write classes for each Api file with the apiTemplateFiles map. * as with models, add multiple entries with different extensions for multiple files per * class @@ -64,23 +64,23 @@ public JMeterCodegen() { apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); - /** + /* * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ templateDir = "JMeter"; - /** + /* * Api Package. Optional, if needed, this can be used in templates */ apiPackage = ""; - /** + /* * Model Package. Optional, if needed, this can be used in templates */ modelPackage = ""; - /** + /* * Reserved words. Override this with reserved words specific to your language */ reservedWords = new HashSet ( @@ -89,7 +89,7 @@ public JMeterCodegen() { "sample2") ); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index c9d558d51ab..5e1a24c331f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -4,22 +4,50 @@ import java.io.File; import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; +/** + * TODO #2017: + * - reuse bean-validation-annotations in Java? + * - pom.xml: maybe add cxf-version property + * - api_test.mustache: add switch for using gzip in test cases? + * + * + * + */ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - public JavaCXFServerCodegen() - { +{ + private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class); + + public static final String USE_BEANVALIDATION = "useBeanValidation"; + + protected boolean useBeanValidation = false; + + + public JavaCXFServerCodegen() + { super(); + apiTestTemplateFiles.clear(); // TODO: add test template + supportsInheritance = true; + + artifactId = "swagger-cxf-server"; + sourceFolder = "gen" + File.separator + "java"; outputFolder = "generated-code/JavaJaxRS-CXF"; - apiTestTemplateFiles.clear(); // TODO: add test template - + + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment //TODO: add doc templates @@ -34,14 +62,45 @@ public JavaCXFServerCodegen() embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; - } + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + + } - @Override - public String getName() - { - return "jaxrs-cxf"; - } + @Override + public void processOpts() + { + super.processOpts(); + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); + this.setUseBeanValidation(useBeanValidationProp); + + // write back as boolean + additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); + } + + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + + writeOptional(outputFolder, new SupportingFile("readme.md", "", "readme.md")); + + writeOptional(outputFolder, new SupportingFile("web.mustache", + ("src/main/webapp/WEB-INF"), "web.xml")); + writeOptional(outputFolder, new SupportingFile("context.xml.mustache", + ("src/main/webapp/WEB-INF"), "context.xml")); + writeOptional(outputFolder, new SupportingFile("jboss-web.xml.mustache", + ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + + } + + @Override + public String getName() + { + return "jaxrs-cxf"; + } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -63,4 +122,8 @@ public String getHelp() { return "Generates a Java JAXRS Server application based on Apache CXF framework."; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } 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 27e95190648..28537c34568 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 @@ -14,12 +14,16 @@ public class JavaClientCodegen extends AbstractJavaCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; + public static final String PARCELABLE_MODEL = "parcelableModel"; + public static final String USE_BEANVALIDATION = "useBeanValidation"; public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; + protected boolean parcelableModel = false; + protected boolean useBeanValidation = false; public JavaClientCodegen() { super(); @@ -31,18 +35,22 @@ public JavaClientCodegen() { modelPackage = "io.swagger.client.model"; cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); + cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); - supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); - supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); - supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - library.setEnum(supportedLibraries); - library.setDefault(DEFAULT_LIBRARY); - cliOptions.add(library); + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + libraryOption.setDefault("okhttp-gson"); + cliOptions.add(libraryOption); + + setLibrary("okhttp-gson"); } @@ -68,6 +76,19 @@ public void processOpts() { if (additionalProperties.containsKey(USE_RX_JAVA)) { this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); } + if (additionalProperties.containsKey(PARCELABLE_MODEL)) { + this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); + } + // put the boolean value back to PARCELABLE_MODEL in additionalProperties + additionalProperties.put(PARCELABLE_MODEL, parcelableModel); + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); + this.setUseBeanValidation(useBeanValidationProp); + + // write back as boolean + additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); + } final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -76,6 +97,7 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); writeOptional(outputFolder, new SupportingFile("build.gradle.mustache", "", "build.gradle")); + writeOptional(outputFolder, new SupportingFile("build.sbt.mustache", "", "build.sbt")); writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); @@ -95,11 +117,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - if (!StringUtils.isEmpty(getLibrary())) { - //TODO: add sbt support to default client - supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - } - //TODO: add doc to retrofit1 and feign if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){ modelDocTemplateFiles.remove("model_doc.mustache"); @@ -116,7 +133,7 @@ public void processOpts() { if ("feign".equals(getLibrary())) { supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); additionalProperties.put("jackson", "true"); - } else if ("okhttp-gson".equals(getLibrary())) { + } else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); @@ -131,8 +148,14 @@ public void processOpts() { } else if("jersey2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); additionalProperties.put("jackson", "true"); - } else if(StringUtils.isEmpty(getLibrary())) { + } else if("jersey1".equals(getLibrary())) { additionalProperties.put("jackson", "true"); + } else { + LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); + } + + if (additionalProperties.containsKey("jackson") ) { + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); } } @@ -164,7 +187,7 @@ public Map postProcessOperations(Map objs) { operation.returnType = "Void"; } if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) - operation.path = operation.path.substring(1); + operation.path = operation.path.substring(1); } } } @@ -175,7 +198,7 @@ public Map postProcessOperations(Map objs) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); if(!BooleanUtils.toBoolean(model.isEnum)) { - final String lib = getLibrary(); + //final String lib = getLibrary(); //Needed imports for Jackson based libraries if(additionalProperties.containsKey("jackson")) { model.imports.add("JsonProperty"); @@ -183,6 +206,11 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert if(additionalProperties.containsKey("gson")) { model.imports.add("SerializedName"); } + } else { // enum class + //Needed imports for Jackson's JsonCreator + if(additionalProperties.containsKey("jackson")) { + model.imports.add("JsonCreator"); + } } } @@ -207,9 +235,15 @@ public Map postProcessModelsEnum(Map objs) { } return objs; } - public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; } + public void setParcelableModel(boolean parcelableModel) { + this.parcelableModel = parcelableModel; + } + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index e82c2893d59..1c856c95382 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -39,6 +39,8 @@ public JavaInflectorServerCodegen() { modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); additionalProperties.put("title", title); + // java inflector uses the jackson lib + additionalProperties.put("jackson", "true"); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java new file mode 100644 index 00000000000..6dcf3f58075 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -0,0 +1,58 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; + +import java.io.File; + +public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen +{ + public JavaJAXRSCXFCDIServerCodegen() + { + artifactId = "swagger-jaxrs-cxf-cdi-server"; + + sourceFolder = "src" + File.separator + "gen" + File.separator + "java"; + + // Three API templates to support CDI injection + apiTemplateFiles.put("apiService.mustache", ".java"); + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + + // Use standard types + typeMapping.put("DateTime", "java.util.Date"); + + // Updated template directory + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; + } + + @Override + public String getName() + { + return "jaxrs-cxf-cdi"; + } + + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + // Reinstate JsonProperty + model.imports.add("JsonProperty"); + } + + @Override + public String getHelp() + { + return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled."; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index 1219af14763..4e1f388e8a4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -18,14 +18,12 @@ import io.swagger.models.Swagger; import io.swagger.util.Json; import org.apache.commons.io.FileUtils; -import com.fasterxml.jackson.core.JsonProcessingException; public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaJAXRSSpecServerCodegen() { super(); - supportsInheritance = true; sourceFolder = "src/main/java"; invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; @@ -36,6 +34,15 @@ public JavaJAXRSSpecServerCodegen() apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; + apiTestTemplateFiles.clear(); // TODO: add api test template + modelTestTemplateFiles.clear(); // TODO: add model test template + + // clear model and api doc template as this codegen + // does not support auto-generated markdown doc at the moment + //TODO: add doc templates + modelDocTemplateFiles.remove("model_doc.mustache"); + apiDocTemplateFiles.remove("api_doc.mustache"); + additionalProperties.put("title", title); typeMapping.put("date", "LocalDate"); @@ -61,8 +68,6 @@ public JavaJAXRSSpecServerCodegen() library.setEnum(supportedLibraries); cliOptions.add(library); - cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); - cliOptions.add(new CliOption("title", "a title describing the application")); } @Override @@ -129,8 +134,6 @@ public void preprocessSwagger(Swagger swagger) { try { String swaggerJson = Json.pretty(swagger); FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson); - } catch (JsonProcessingException e) { - throw new RuntimeException(e.getMessage(), e.getCause()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e.getCause()); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index df43ab822d7..d09bb34990e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -9,6 +9,15 @@ import org.apache.commons.lang3.StringUtils; public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { + + protected static final String LIBRARY_JERSEY1 = "jersey1"; + protected static final String LIBRARY_JERSEY2 = "jersey2"; + + /** + * Default library template to use. (Default:{@value #DEFAULT_LIBRARY}) + */ + public static final String DEFAULT_LIBRARY = LIBRARY_JERSEY2; + public JavaJerseyServerCodegen() { super(); @@ -29,10 +38,10 @@ public JavaJerseyServerCodegen() { CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - supportedLibraries.put("jersey1", "Jersey core 1.x"); - supportedLibraries.put("jersey2", "Jersey core 2.x (default)"); + supportedLibraries.put(LIBRARY_JERSEY1, "Jersey core 1.x"); + supportedLibraries.put(LIBRARY_JERSEY2, "Jersey core 2.x"); library.setEnum(supportedLibraries); - library.setDefault("jersey1"); + library.setDefault(DEFAULT_LIBRARY); cliOptions.add(library); @@ -71,9 +80,9 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert public void processOpts() { super.processOpts(); - // set jersey2 as default + // use default library if unset if (StringUtils.isEmpty(library)) { - setLibrary("jersey2"); + setLibrary(DEFAULT_LIBRARY); } if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { @@ -95,6 +104,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "RFC3339DateFormat.java")); writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java")); writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index 2aff70422da..7d026403a00 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -67,10 +67,12 @@ public void processOpts() { (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); + supportingFiles.add(new SupportingFile("JacksonConfig.mustache", + (sourceFolder + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RFC3339DateFormat.java")); if ("joda".equals(dateLibrary)) { - supportingFiles.add(new SupportingFile("JacksonConfig.mustache", - (sourceFolder + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java")); supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index c20a70d4028..76ef0d38c90 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -113,7 +113,7 @@ public JavascriptClientCodegen() { ); languageSpecificPrimitives = new HashSet( - Arrays.asList("String", "Boolean", "Integer", "Number", "Array", "Object", "Date", "File") + Arrays.asList("String", "Boolean", "Number", "Array", "Object", "Date", "File") ); defaultIncludes = new HashSet(languageSpecificPrimitives); @@ -126,17 +126,17 @@ public JavascriptClientCodegen() { typeMapping.put("List", "Array"); typeMapping.put("boolean", "Boolean"); typeMapping.put("string", "String"); - typeMapping.put("int", "Integer"); // Huh? What is JS Integer? + typeMapping.put("int", "Number"); typeMapping.put("float", "Number"); typeMapping.put("number", "Number"); - typeMapping.put("DateTime", "Date"); // Should this be dateTime? - typeMapping.put("date", "Date"); // Should this be date? - typeMapping.put("long", "Integer"); - typeMapping.put("short", "Integer"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("date", "Date"); + typeMapping.put("long", "Number"); + typeMapping.put("short", "Number"); typeMapping.put("char", "String"); typeMapping.put("double", "Number"); typeMapping.put("object", "Object"); - typeMapping.put("integer", "Integer"); + typeMapping.put("integer", "Number"); // binary not supported in JavaScript client right now, using String as a workaround typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger docs. typeMapping.put("binary", "String"); @@ -171,6 +171,8 @@ public JavascriptClientCodegen() { cliOptions.add(new CliOption(USE_INHERITANCE, "use JavaScript prototype chains & delegation for inheritance") .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } @Override @@ -192,6 +194,15 @@ public String getHelp() { public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + if (additionalProperties.containsKey(PROJECT_NAME)) { setProjectName(((String) additionalProperties.get(PROJECT_NAME))); } @@ -223,6 +234,7 @@ public void processOpts() { setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE))); } else { supportsInheritance = true; + supportsMixins = true; } if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) { setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS))); @@ -386,6 +398,7 @@ public void setUsePromises(boolean usePromises) { public void setUseInheritance(boolean useInheritance) { this.supportsInheritance = useInheritance; + this.supportsMixins = useInheritance; } public void setEmitModelMethods(boolean emitModelMethods) { @@ -762,9 +775,11 @@ private String getModelledType(String dataType) { + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; } + /* private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) { return "{" + getJSDocType(cm, cp) + "}"; } + */ private String getJSDocType(CodegenModel cm, CodegenProperty cp) { if (Boolean.TRUE.equals(cp.isContainer)) { @@ -787,9 +802,11 @@ private boolean isModelledType(CodegenProperty cp) { return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType); } + /* private String getJSDocTypeWithBraces(CodegenParameter cp) { return "{" + getJSDocType(cp) + "}"; } + */ private String getJSDocType(CodegenParameter cp) { String dataType = trimBrackets(cp.dataType); @@ -808,10 +825,12 @@ private boolean isModelledType(CodegenParameter cp) { return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType); } + /* private String getJSDocTypeWithBraces(CodegenOperation co) { String jsDocType = getJSDocType(co); return jsDocType == null ? null : "{" + jsDocType + "}"; } + */ private String getJSDocType(CodegenOperation co) { String returnType = trimBrackets(co.returnType); @@ -860,10 +879,10 @@ public Map postProcessOperations(Map objs) { // Store JSDoc type specification into vendor-extension: x-jsdoc-type. for (CodegenParameter cp : operation.allParams) { - String jsdocType = getJSDocTypeWithBraces(cp); + String jsdocType = getJSDocType(cp); cp.vendorExtensions.put("x-jsdoc-type", jsdocType); } - String jsdocType = getJSDocTypeWithBraces(operation); + String jsdocType = getJSDocType(operation); operation.vendorExtensions.put("x-jsdoc-type", jsdocType); } } @@ -883,13 +902,13 @@ public Map postProcessModels(Map objs) { // NOTE: can't use 'mandatory' as it is built from ModelImpl.getRequired(), which sorts names // alphabetically and in any case the document order of 'required' and 'properties' can differ. List required = new ArrayList<>(); - List allRequired = supportsInheritance ? new ArrayList() : required; + List allRequired = supportsInheritance || supportsMixins ? new ArrayList() : required; cm.vendorExtensions.put("x-required", required); cm.vendorExtensions.put("x-all-required", allRequired); for (CodegenProperty var : cm.vars) { // Add JSDoc @type value for this property. - String jsDocType = getJSDocTypeWithBraces(cm, var); + String jsDocType = getJSDocType(cm, var); var.vendorExtensions.put("x-jsdoc-type", jsDocType); if (Boolean.TRUE.equals(var.required)) { @@ -897,7 +916,7 @@ public Map postProcessModels(Map objs) { } } - if (supportsInheritance) { + if (supportsInheritance || supportsMixins) { for (CodegenProperty var : cm.allVars) { if (Boolean.TRUE.equals(var.required)) { allRequired.add(var); @@ -1002,25 +1021,12 @@ public String toEnumName(CodegenProperty property) { @Override public String toEnumVarName(String value, String datatype) { - return value; - /* - // number - if ("Integer".equals(datatype) || "Number".equals(datatype)) { - String varName = "NUMBER_" + value; - varName = varName.replaceAll("-", "MINUS_"); - varName = varName.replaceAll("\\+", "PLUS_"); - varName = varName.replaceAll("\\.", "_DOT_"); - return varName; + // for symbol, e.g. $, # + if (getSymbolName(value) != null) { + return (getSymbolName(value)).toUpperCase(); } - // string - String var = value.replaceAll("\\W+", "_").replaceAll("_+", "_").toUpperCase(); - if (var.matches("\\d.*")) { - return "_" + var; - } else { - return var; - } - */ + return value; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 0371eee5e75..0b619824c4d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -70,6 +70,19 @@ public JavascriptClosureAngularClientCodegen() { embeddedTemplateDir = templateDir = "Javascript-Closure-Angular"; apiPackage = "API.Client"; modelPackage = "API.Client"; + + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } + + @Override + public void processOpts() { + super.processOpts(); + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index 700bdfd3a50..5dd35ba1b0f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -10,10 +10,9 @@ import java.util.Map; import java.util.TreeMap; -public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig { - - // source folder where to write the files - protected String sourceFolder = ""; +public class LumenServerCodegen extends AbstractPhpCodegen +{ + @SuppressWarnings("hiding") protected String apiVersion = "1.0.0"; /** @@ -23,7 +22,7 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig * @see io.swagger.codegen.CodegenType */ public CodegenType getTag() { - return CodegenType.CLIENT; + return CodegenType.SERVER; } /** @@ -43,127 +42,59 @@ public String getName() { * @return A string value for the help message */ public String getHelp() { - return "Generates a LumenServerCodegen client library."; + return "Generates a LumenServerCodegen server library."; } public LumenServerCodegen() { super(); - // set the output folder here - outputFolder = "lumen"; - String packagePath = ""; - - /** - * 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.put( - // "model.mustache", // the template to use - // ".sample"); // the extension for each file to write + embeddedTemplateDir = templateDir = "lumen"; - /** - * 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 + /* + * packPath */ - // apiTemplateFiles.put( - // "api.mustache", // the template to use - // ".sample"); // the extension for each file to write - - - // no api files - // apiTemplateFiles.clear(); - apiTemplateFiles.put("api.mustache", ".php"); - - // embeddedTemplateDir = templateDir = "slim"; + invokerPackage = "lumen"; + packagePath = ""; - /** - * 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. - */ - templateDir = "lumen"; - - /** + /* * Api Package. Optional, if needed, this can be used in templates */ apiPackage = "app.Http.Controllers"; - /** + /* * Model Package. Optional, if needed, this can be used in templates */ modelPackage = "models"; - /** - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet ( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); + // template files want to be ignored + modelTemplateFiles.clear(); + apiTestTemplateFiles.clear(); + apiDocTemplateFiles.clear(); + modelDocTemplateFiles.clear(); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); - /** + /* * 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("composer.mustache", packagePath, "composer.json")); - supportingFiles.add(new SupportingFile("readme.md", packagePath, "readme.md")); - supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + "bootstrap", "app.php")); - supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php")); - supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + "app", "User.php")); - supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); - supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); - supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + "app" + File.separator + "Http", "routes.php")); + supportingFiles.add(new SupportingFile("composer.mustache", packagePath + File.separator + srcBasePath, "composer.json")); + supportingFiles.add(new SupportingFile("readme.md", packagePath + File.separator + srcBasePath, "readme.md")); + supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + srcBasePath + File.separator + "bootstrap", "app.php")); + supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + srcBasePath + File.separator + "public", "index.php")); + supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + srcBasePath + File.separator + "app", "User.php")); + supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); + supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); + supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http", "routes.php")); - supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); - supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); + supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); + supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); - /** - * Language Specific Primitives. These types will not trigger imports by - * the client generator - */ - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Type1", // replace these with your types - "Type2") - ); - } - - /** - * 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) { - return "_" + name; // add an underscore to the name - } - - /** - * Location to write model files. You can use the modelPackage() as defined when the class is - * instantiated - */ - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - /** - * Location to write api files. You can use the apiPackage() as defined when the class is - * instantiated - */ - @Override - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);//"/app/Http/controllers"; } // override with any special post-processing @@ -185,57 +116,4 @@ public int compare(CodegenOperation lhs, CodegenOperation rhs) { return objs; } - /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types - * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } - - /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) - return toModelName(type); - } - else - type = swaggerType; - return toModelName(type); - } - - @Override - public String escapeQuotationMark(String input) { - // remove ' to avoid code injection - return input.replace("'", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - } diff --git a/modules/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 3eec3751364..571bcdef920 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 @@ -222,7 +222,7 @@ public Map postProcessAllModels(final Map models } private void postProcessParentModels(final Map models) { - log.info("Processing parents: " + parentModels); + log.debug("Processing parents: " + parentModels); for (final String parent : parentModels) { final CodegenModel parentModel = modelByName(parent, models); parentModel.hasChildren = true; @@ -301,7 +301,7 @@ public String toEnumVarName(final String name, final String datatype) { } else { result = enumName; } - log.info(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName)); + log.debug(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName)); return result; } @@ -313,7 +313,7 @@ public String toApiName(final String name) { } else { apiName = capitalize(name); } - log.info(String.format("toApiName('%s') = '%s'", name, apiName)); + log.debug(String.format("toApiName('%s') = '%s'", name, apiName)); return apiName; } @@ -334,7 +334,7 @@ public String toModelImport(final String name) { } else { result = null; } - log.info(String.format("toModelImport('%s') = '%s'", name, result)); + log.debug(String.format("toModelImport('%s') = '%s'", name, result)); return result; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 002496005e1..184027dd42b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -34,7 +34,7 @@ public NodeJSServerCodegen() { // set the output folder here outputFolder = "generated-code/nodejs"; - /** + /* * 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 @@ -42,7 +42,7 @@ public NodeJSServerCodegen() { */ 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 @@ -51,13 +51,13 @@ public NodeJSServerCodegen() { "controller.mustache", // the template to use ".js"); // the extension for each file to write - /** + /* * 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 = "nodejs"; - /** + /* * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( @@ -69,14 +69,14 @@ public NodeJSServerCodegen() { "void", "while", "with", "yield") ); - /** + /* * 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); - /** + /* * 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 @@ -320,4 +320,14 @@ public String removeNonNameElementToCamelCase(String name) { return removeNonNameElementToCamelCase(name, "[-:;#]"); } + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index e028083a74b..cb4b76c32bb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -46,7 +46,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public ObjcClientCodegen() { super(); - + supportsInheritance = true; outputFolder = "generated-code" + File.separator + "objc"; modelTemplateFiles.put("model-header.mustache", ".h"); modelTemplateFiles.put("model-body.mustache", ".m"); @@ -167,6 +167,8 @@ public ObjcClientCodegen() { cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") .defaultValue("https://github.com/swagger-api/swagger-codegen")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } @Override @@ -188,6 +190,14 @@ public String getHelp() { public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + if (additionalProperties.containsKey(POD_NAME)) { setPodName((String) additionalProperties.get(POD_NAME)); } @@ -349,7 +359,7 @@ public String getTypeDeclaration(Property p) { return getSwaggerType(p) + "*"; } } - return getSwaggerType(p) + "*"; + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; } } else { String swaggerType = getSwaggerType(p); @@ -504,8 +514,8 @@ public String toVarName(String name) { } // if name starting with special word, escape with '_' - for(int i =0; i < specialWords.length; i++) { - if (name.matches("(?i:^" + specialWords[i] + ".*)")) + for (String specialWord : specialWords) { + if (name.matches("(?i:^" + specialWord + ".*)")) name = escapeSpecialWord(name); } @@ -614,7 +624,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "@\"" + dp.getDefault().toString() + "\""; + return "@\"" + dp.getDefault() + "\""; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -703,6 +713,8 @@ public void setParameterExampleValue(CodegenParameter p) { example = "2013-10-20T19:20:30+01:00"; } example = "@\"" + escapeText(example) + "\""; + } else if ("NSData".equalsIgnoreCase(type)) { + example = "1234"; } else if (!languageSpecificPrimitives.contains(type)) { // type is a model class, e.g. User type = type.replace("*", ""); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 15ec94188e1..db892f8a7ff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -42,6 +42,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public PerlClientCodegen() { super(); + + // clear import mapping (from default generator) as perl does not use it + // at the moment + importMapping.clear(); + modelPackage = File.separatorChar + "Object"; outputFolder = "generated-code" + File.separatorChar + "perl"; modelTemplateFiles.put("object.mustache", ".pm"); @@ -227,7 +232,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; + return "'" + dp.getDefault() + "'"; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -396,9 +401,9 @@ public void setParameterExampleValue(CodegenParameter p) { p.example = "'" + p.example + "'"; } else if (Boolean.TRUE.equals(p.isBoolean)) { if (Boolean.parseBoolean(p.example)) - p.example = new String("1"); + p.example = "1"; else - p.example = new String("0"); + p.example = "0"; } else if (Boolean.TRUE.equals(p.isDateTime) || Boolean.TRUE.equals(p.isDate)) { p.example = "DateTime->from_epoch(epoch => str2time('" + p.example + "'))"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index feaf63d4e39..232bf9fa56c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -13,6 +13,8 @@ import java.io.File; import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,6 +52,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public PhpClientCodegen() { super(); + // clear import mapping (from default generator) as php does not use it + // at the moment + importMapping.clear(); + + supportsInheritance = true; outputFolder = "generated-code" + File.separator + "php"; modelTemplateFiles.put("model.mustache", ".php"); @@ -96,7 +103,9 @@ public PhpClientCodegen() { // provide primitives to mustache template - String primitives = "'" + StringUtils.join(languageSpecificPrimitives, "', '") + "'"; + List sortedLanguageSpecificPrimitives= new ArrayList(languageSpecificPrimitives); + Collections.sort(sortedLanguageSpecificPrimitives); + String primitives = "'" + StringUtils.join(sortedLanguageSpecificPrimitives, "', '") + "'"; additionalProperties.put("primitives", primitives); // ref: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types @@ -132,6 +141,8 @@ public PhpClientCodegen() { cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } public String getPackagePath() { @@ -139,6 +150,10 @@ public String getPackagePath() { } public String toPackagePath(String packageName, String basePath) { + return (getPackagePath() + File.separatorChar + toSrcPath(packageName, basePath)); + } + + public String toSrcPath(String packageName, String basePath) { packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if (basePath != null && basePath.length() > 0) { basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. @@ -158,13 +173,13 @@ public String toPackagePath(String packageName, String basePath) { regLastPathSeparator = "\\\\$"; } - return (getPackagePath() + File.separatorChar + basePath - // Replace period, backslash, forward slash with file separator in package name - + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) - // Trim prefix file separators from package path - .replaceAll(regFirstPathSeparator, "")) - // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + return (basePath + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) + // Trim prefix file separators from package path + .replaceAll(regFirstPathSeparator, "")) + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator+ "$", ""); } @Override @@ -195,6 +210,14 @@ public String getHelp() { public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + if (additionalProperties.containsKey(PACKAGE_PATH)) { this.setPackagePath((String) additionalProperties.get(PACKAGE_PATH)); } else { @@ -257,6 +280,12 @@ public void processOpts() { additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); + // make api and model src path available in mustache template + additionalProperties.put("apiSrcPath", "./" + toSrcPath(apiPackage, srcBasePath)); + additionalProperties.put("modelSrcPath", "./" + toSrcPath(modelPackage, srcBasePath)); + additionalProperties.put("apiTestPath", "./" + testBasePath + "/" + apiDirName); + additionalProperties.put("modelTestPath", "./" + testBasePath + "/" + modelDirName); + // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); @@ -271,7 +300,9 @@ public void processOpts() { supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); + supportingFiles.add(new SupportingFile("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")); // apache v2 license supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE")); @@ -428,7 +459,7 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - // remove [ + // remove [ name = name.replaceAll("\\]", ""); // Note: backslash ("\\") is allowed for e.g. "\\DateTime" @@ -453,7 +484,7 @@ public String toModelName(String name) { if (!name.matches("^\\\\.*")) { name = modelNamePrefix + name + modelNameSuffix; } - + // camelize the model name // phone_number => PhoneNumber return camelize(name); @@ -498,7 +529,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; + return "'" + dp.getDefault() + "'"; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -617,7 +648,7 @@ public String toEnumDefaultValue(String value, String datatype) { public String toEnumVarName(String name, String datatype) { // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); @@ -640,6 +671,9 @@ public String toEnumVarName(String name, String datatype) { public String toEnumName(CodegenProperty property) { String enumName = underscore(toModelName(property.name)).toUpperCase(); + // remove [] for array or map of enum + enumName = enumName.replace("[]", ""); + if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { 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 f42e662d0fa..bd275691428 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 @@ -1,605 +1,624 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenParameter; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.*; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String packageName; - protected String packageVersion; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - - protected Map regexModifiers; - - private String testFolder; - - public PythonClientCodegen() { - super(); - - modelPackage = "models"; - apiPackage = "api"; - outputFolder = "generated-code" + File.separatorChar + "python"; - - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - - modelTestTemplateFiles.put("model_test.mustache", ".py"); - apiTestTemplateFiles.put("api_test.mustache", ".py"); - - embeddedTemplateDir = templateDir = "python"; - - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); - - testFolder = "test"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("list"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("str"); - languageSpecificPrimitives.add("datetime"); - languageSpecificPrimitives.add("date"); - languageSpecificPrimitives.add("object"); - - typeMapping.clear(); - typeMapping.put("integer", "int"); - typeMapping.put("float", "float"); - typeMapping.put("number", "float"); - typeMapping.put("long", "int"); - typeMapping.put("double", "float"); - typeMapping.put("array", "list"); - typeMapping.put("map", "dict"); - typeMapping.put("boolean", "bool"); - typeMapping.put("string", "str"); - typeMapping.put("date", "date"); - typeMapping.put("DateTime", "datetime"); - typeMapping.put("object", "object"); - typeMapping.put("file", "file"); - // TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "str"); - typeMapping.put("ByteArray", "str"); - // map uuid to string for the time being - typeMapping.put("UUID", "str"); - - // from https://docs.python.org/release/2.5.4/ref/keywords.html - setReservedWordsLowerCase( - Arrays.asList( - // local variable name used in API methods (endpoints) - "all_params", "resource_path", "path_params", "query_params", - "header_params", "form_params", "local_var_files", "body_params", "auth_settings", - // @property - "property", - // python reserved words - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try", "self")); - - regexModifiers = new HashMap(); - regexModifiers.put('i', "IGNORECASE"); - regexModifiers.put('l', "LOCALE"); - regexModifiers.put('m', "MULTILINE"); - regexModifiers.put('s', "DOTALL"); - regexModifiers.put('u', "UNICODE"); - regexModifiers.put('x', "VERBOSE"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") - .defaultValue("swagger_client")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") - .defaultValue("1.0.0")); - cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, - CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); - } - - @Override - public void processOpts() { - super.processOpts(); - Boolean excludeTests = false; - - if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { - excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - 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); - - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - - 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("LICENSE", "", "LICENSE")); - - supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); - supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); - supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); - supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); - - supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); - supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); - supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py")); - supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); - - if(Boolean.FALSE.equals(excludeTests)) { - supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py")); - } - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); - } - - private static String dropDots(String str) { - return str.replaceAll("\\.", "_"); - } - - @Override - public void postProcessParameter(CodegenParameter parameter){ - postProcessPattern(parameter.pattern, parameter.vendorExtensions); - } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - postProcessPattern(property.pattern, property.vendorExtensions); - } - - /* - * The swagger pattern spec follows the Perl convention and style of modifiers. Python - * does not support this in as natural a way so it needs to convert it. See - * https://docs.python.org/2/howto/regex.html#compilation-flags for details. - */ - public void postProcessPattern(String pattern, Map vendorExtensions){ - if(pattern != null) { - int i = pattern.lastIndexOf('/'); - - //Must follow Perl /pattern/modifiers convention - if(pattern.charAt(0) != '/' || i < 2) { - throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. "+pattern+" is not valid."); - } - - String regex = pattern.substring(1, i).replace("'", "\'"); - List modifiers = new ArrayList(); - - for(char c : pattern.substring(i).toCharArray()) { - if(regexModifiers.containsKey(c)) { - String modifier = regexModifiers.get(c); - modifiers.add(modifier); - } - } - - vendorExtensions.put("x-regex", regex); - vendorExtensions.put("x-modifiers", modifiers); - } - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "python"; - } - - @Override - public String getHelp() { - return "Generates a Python client library."; - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - - @Override - public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String apiTestFileFolder() { - return outputFolder + File.separatorChar + testFolder; - } - - @Override - public String modelTestFileFolder() { - return outputFolder + File.separatorChar + testFolder; - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")"; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - type = toModelName(swaggerType); - } - return type; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // remove dollar sign - name = name.replaceAll("$", ""); - - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) { - name = name.toLowerCase(); - } - - // underscore the variable name - // petId => pet_id - name = underscore(name); - - // remove leading underscore - name = name.replaceAll("^_*", ""); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // remove dollar sign - name = name.replaceAll("$", ""); - - // 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) - } - - // model name starts with number - if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); - name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // remove dollar sign - name = name.replaceAll("$", ""); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name))); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); - name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - // underscore the model file name - // PhoneNumber => phone_number - return underscore(dropDots(name)); - } - - @Override - public String toModelTestFilename(String name) { - return "test_" + toModelFilename(name); - }; - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; - } - - @Override - public String toApiTestFilename(String name) { - return "test_" + toApiFilename(name); - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } - - @Override - public String toApiVarName(String name) { - if (name.length() == 0) { - return "default_api"; - } - return underscore(name) + "_api"; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty (should not occur as an auto-generated method name will be used) - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // 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(sanitizeName(operationId)); - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public void setPackageVersion(String packageVersion) { - this.packageVersion = packageVersion; - } - - /** - * Generate Python package name from String `packageName` - * - * (PEP 0008) Python packages should also have short, all-lowercase names, - * although the use of underscores is discouraged. - * - * @param packageName Package name - * @return Python package name that conforms to PEP 0008 - */ - @SuppressWarnings("static-method") - public String generatePackageName(String packageName) { - return underscore(packageName.replaceAll("[^\\w]+", "")); - } - - /** - * Return the default value of the property - * - * @param p Swagger property object - * @return string presentation of the default value of the property - */ - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; - } - } 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 DateProperty) { - // TODO - } else if (p instanceof DateTimeProperty) { - // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (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 setParameterExampleValue(CodegenParameter p) { - String example; - - if (p.defaultValue == null) { - example = p.example; - } else { - example = p.defaultValue; - } - - String type = p.baseType; - if (type == null) { - type = p.dataType; - } - - if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "'" + escapeText(example) + "'"; - } else if ("Integer".equals(type) || "int".equals(type)) { - if (example == null) { - example = "56"; - } - } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } - } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { - if (example == null) { - example = "True"; - } - } else if ("file".equalsIgnoreCase(type)) { - if (example == null) { - example = "/path/to/file"; - } - example = "'" + escapeText(example) + "'"; - } else if ("Date".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'"; - } else if ("DateTime".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20T19:20:30+01:00"; - } - example = "'" + escapeText(example) + "'"; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - example = this.packageName + "." + type + "()"; - } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); - } - - if (example == null) { - example = "NULL"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "[" + example + "]"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "{'key': " + example + "}"; - } - - p.example = example; - } - - @Override - public String escapeQuotationMark(String input) { - // remove ' to avoid code injection - return input.replace("'", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - // remove multiline comment - return input.replace("'''", "'_'_'"); - } - -} +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String packageName; + protected String packageVersion; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + protected Map regexModifiers; + + private String testFolder; + + public PythonClientCodegen() { + super(); + + // clear import mapping (from default generator) as python does not use it + // at the moment + importMapping.clear(); + + modelPackage = "models"; + apiPackage = "api"; + outputFolder = "generated-code" + File.separatorChar + "python"; + + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + + modelTestTemplateFiles.put("model_test.mustache", ".py"); + apiTestTemplateFiles.put("api_test.mustache", ".py"); + + embeddedTemplateDir = templateDir = "python"; + + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + testFolder = "test"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("str"); + languageSpecificPrimitives.add("datetime"); + languageSpecificPrimitives.add("date"); + languageSpecificPrimitives.add("object"); + + typeMapping.clear(); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("number", "float"); + typeMapping.put("long", "int"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "dict"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "str"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); + typeMapping.put("object", "object"); + typeMapping.put("file", "file"); + // TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "str"); + typeMapping.put("ByteArray", "str"); + // map uuid to string for the time being + typeMapping.put("UUID", "str"); + + // from https://docs.python.org/release/2.5.4/ref/keywords.html + setReservedWordsLowerCase( + Arrays.asList( + // local variable name used in API methods (endpoints) + "all_params", "resource_path", "path_params", "query_params", + "header_params", "form_params", "local_var_files", "body_params", "auth_settings", + // @property + "property", + // python reserved words + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try", "self")); + + regexModifiers = new HashMap(); + regexModifiers.put('i', "IGNORECASE"); + regexModifiers.put('l', "LOCALE"); + regexModifiers.put('m', "MULTILINE"); + regexModifiers.put('s', "DOTALL"); + regexModifiers.put('u', "UNICODE"); + regexModifiers.put('x', "VERBOSE"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") + .defaultValue("swagger_client")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } + + @Override + public void processOpts() { + super.processOpts(); + Boolean excludeTests = false; + + if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { + excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + else { + setPackageName("swagger_client"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + else { + setPackageVersion("1.0.0"); + } + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + 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("LICENSE", "", "LICENSE")); + + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); + supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); + supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); + supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); + + supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); + supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); + supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py")); + supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); + + if(Boolean.FALSE.equals(excludeTests)) { + supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py")); + } + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + + @Override + public void postProcessParameter(CodegenParameter parameter){ + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + } + + /* + * The swagger pattern spec follows the Perl convention and style of modifiers. Python + * does not support this in as natural a way so it needs to convert it. See + * https://docs.python.org/2/howto/regex.html#compilation-flags for details. + */ + public void postProcessPattern(String pattern, Map vendorExtensions){ + if(pattern != null) { + int i = pattern.lastIndexOf('/'); + + //Must follow Perl /pattern/modifiers convention + if(pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. "+pattern+" is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\\'"); + List modifiers = new ArrayList(); + + for(char c : pattern.substring(i).toCharArray()) { + if(regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "python"; + } + + @Override + public String getHelp() { + return "Generates a Python client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + + @Override + public String apiFileFolder() { + return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separatorChar + testFolder; + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separatorChar + testFolder; + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } + return type; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // remove dollar sign + name = name.replaceAll("$", ""); + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // underscore the variable name + // petId => pet_id + name = underscore(name); + + // remove leading underscore + name = name.replaceAll("^_*", ""); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "param_callback"; + } + + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + // remove dollar sign + name = name.replaceAll("$", ""); + + // 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) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + // remove dollar sign + name = name.replaceAll("$", ""); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name))); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // underscore the model file name + // PhoneNumber => phone_number + return underscore(dropDots(name)); + } + + @Override + public String toModelTestFilename(String name) { + return "test_" + toModelFilename(name); + }; + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } + + @Override + public String toApiTestFilename(String name) { + return "test_" + toApiFilename(name); + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toApiVarName(String name) { + if (name.length() == 0) { + return "default_api"; + } + return underscore(name) + "_api"; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty (should not occur as an auto-generated method name will be used) + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // 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(sanitizeName(operationId)); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + /** + * Generate Python package name from String `packageName` + * + * (PEP 0008) Python packages should also have short, all-lowercase names, + * although the use of underscores is discouraged. + * + * @param packageName Package name + * @return Python package name that conforms to PEP 0008 + */ + @SuppressWarnings("static-method") + public String generatePackageName(String packageName) { + return underscore(packageName.replaceAll("[^\\w]+", "")); + } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "False"; + else + return "True"; + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (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 setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "'" + escapeText(example) + "'"; + } else if ("Integer".equals(type) || "int".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("file".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "'" + escapeText(example) + "'"; + } else if ("Date".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'"; + } else if ("DateTime".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "'" + escapeText(example) + "'"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = this.packageName + "." + type + "()"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "{'key': " + example + "}"; + } + + p.example = example; + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + // remove multiline comment + return input.replace("'''", "'_'_'"); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 46999eccbe1..f3179688c32 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -11,6 +11,7 @@ import io.swagger.models.properties.DecimalProperty; import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.BaseIntegerProperty; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; @@ -40,7 +41,7 @@ public Qt5CPPGenerator() { // set the output folder here outputFolder = "generated-code/qt5cpp"; - /** + /* * 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 @@ -54,7 +55,7 @@ public Qt5CPPGenerator() { "model-body.mustache", ".cpp"); - /** + /* * 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 @@ -67,13 +68,13 @@ public Qt5CPPGenerator() { "api-body.mustache", // the template to use ".cpp"); // the extension for each file to write - /** + /* * 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 = "qt5cpp"; - /** + /* * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( @@ -82,14 +83,14 @@ public Qt5CPPGenerator() { "sample2") ); - /** + /* * 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("prefix", PREFIX); - /** + /* * Language Specific Primitives. These types will not trigger imports by * the client generator */ @@ -124,6 +125,7 @@ public Qt5CPPGenerator() { //TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "QString"); + typeMapping.put("ByteArray", "QByteArray"); importMapping = new HashMap(); @@ -138,6 +140,7 @@ public Qt5CPPGenerator() { systemIncludes.add("QMap"); systemIncludes.add("QDate"); systemIncludes.add("QDateTime"); + systemIncludes.add("QByteArray"); } /** @@ -268,6 +271,10 @@ public String toDefaultValue(Property p) { return "0"; } else if (p instanceof LongProperty) { return "0L"; + } else if (p instanceof BaseIntegerProperty) { + // catchall for any other format of the swagger specifiction + // integer type not explicitly handled above + return "0"; } else if (p instanceof DecimalProperty) { return "0.0"; } else if (p instanceof MapProperty) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java index e03622b5919..5147d4a5b00 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -281,8 +281,8 @@ public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_controllers"; + // e.g. DefaultController => defaults_controller.rb + return underscore(name) + "s_controller"; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index e58199e1b70..f67b928f870 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -30,6 +30,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; public static final String GEM_VERSION = "gemVersion"; public static final String GEM_LICENSE = "gemLicense"; + public static final String GEM_REQUIRED_RUBY_VERSION = "gemRequiredRubyVersion"; public static final String GEM_HOMEPAGE = "gemHomepage"; public static final String GEM_SUMMARY = "gemSummary"; public static final String GEM_DESCRIPTION = "gemDescription"; @@ -42,6 +43,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { protected String specFolder = "spec"; protected String libFolder = "lib"; protected String gemLicense = "Apache-2.0"; + protected String gemRequiredRubyVersion = ">= 1.9"; protected String gemHomepage = "http://swagger.io"; protected String gemSummary = "A ruby wrapper for the swagger APIs"; protected String gemDescription = "This gem maps to a swagger API"; @@ -54,6 +56,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public RubyClientCodegen() { super(); + + // clear import mapping (from default generator) as ruby does not use it + // at the moment + importMapping.clear(); + modelPackage = "models"; apiPackage = "api"; outputFolder = "generated-code" + File.separator + "ruby"; @@ -138,6 +145,9 @@ public RubyClientCodegen() { cliOptions.add(new CliOption(GEM_LICENSE, "gem license. "). defaultValue("Apache-2.0")); + cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. "). + defaultValue(">= 1.9")); + cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. "). defaultValue("http://swagger.io")); @@ -151,12 +161,23 @@ public RubyClientCodegen() { cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated"). + defaultValue(Boolean.TRUE.toString())); + } @Override public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + if (additionalProperties.containsKey(GEM_NAME)) { setGemName((String) additionalProperties.get(GEM_NAME)); } @@ -187,6 +208,10 @@ public void processOpts() { setGemLicense((String) additionalProperties.get(GEM_LICENSE)); } + if (additionalProperties.containsKey(GEM_REQUIRED_RUBY_VERSION)) { + setGemRequiredRubyVersion((String) additionalProperties.get(GEM_REQUIRED_RUBY_VERSION)); + } + if (additionalProperties.containsKey(GEM_HOMEPAGE)) { setGemHomepage((String) additionalProperties.get(GEM_HOMEPAGE)); } @@ -225,7 +250,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); // test files should not be overwritten writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec")); @@ -544,7 +568,7 @@ public String toEnumValue(String value, String datatype) { public String toEnumVarName(String name, String datatype) { // number if ("Integer".equals(datatype) || "Float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); @@ -693,6 +717,10 @@ public void setGemLicense(String gemLicense) { this.gemLicense = gemLicense; } + public void setGemRequiredRubyVersion(String gemRequiredRubyVersion) { + this.gemRequiredRubyVersion = gemRequiredRubyVersion; + } + public void setGemHomepage(String gemHomepage) { this.gemHomepage = gemHomepage; } @@ -723,4 +751,5 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { return input.replace("=end", "=_end").replace("=begin", "=_begin"); } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 157d650a42f..ea4539133af 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -4,40 +4,22 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; import java.io.File; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; import org.apache.commons.lang3.StringUtils; -public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-scala-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; +public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String authScheme = ""; protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean authPreemptive; protected boolean asyncHttpClient = !authScheme.isEmpty(); + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-scala-client"; + protected String artifactVersion = "1.0.0"; public ScalaClientCodegen() { super(); @@ -117,134 +99,93 @@ public ScalaClientCodegen() { typeMapping.put("binary", "String"); typeMapping.put("ByteArray", "String"); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "Any", - "List", - "Map") - ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); } @Override - public String getName() { - return "scala"; + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { + setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + } } - - @Override - public String getHelp() { - return "Generates a Scala client library."; + + public void setModelPropertyNaming(String naming) { + if ("original".equals(naming) || "camelCase".equals(naming) || + "PascalCase".equals(naming) || "snake_case".equals(naming)) { + this.modelPropertyNaming = naming; + } else { + throw new IllegalArgumentException("Invalid model property naming '" + + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } } - @Override - public String escapeReservedWord(String name) { - return "_" + name; + public String getModelPropertyNaming() { + return this.modelPropertyNaming; } - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + if("_".equals(name)) { + name = "_u"; + } + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + name = getNameUsingModelPropertyNaming(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; } @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getNameUsingModelPropertyNaming(String name) { + switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { + case original: return name; + case camelCase: return camelize(name, true); + case PascalCase: return camelize(name); + case snake_case: return underscore(name); + default: throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); } - return super.getTypeDeclaration(p); + } @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); + public CodegenType getTag() { + return CodegenType.CLIENT; } @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else { - return null; - } + public String getName() { + return "scala"; } @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "null"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - return "null"; - } else if (p instanceof FloatProperty) { - return "null"; - } else if (p instanceof IntegerProperty) { - return "null"; - } else if (p instanceof LongProperty) { - return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap[String, " + inner + "]() "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; - } else { - return "null"; - } + public String getHelp() { + return "Generates a Scala client library."; } - @Override public String toOperationId(String operationId) { // throw exception if method name is empty @@ -260,91 +201,35 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } - @Override - public Map postProcessModels(Map objs) { - // remove model imports to avoid warnings for importing class in the same package in Scala - List> imports = (List>) objs.get("imports"); - final String prefix = modelPackage() + "."; - Iterator> iterator = imports.iterator(); - while (iterator.hasNext()) { - String _import = iterator.next().get("import"); - if (_import.startsWith(prefix)) iterator.remove(); - } - return objs; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - if("_".equals(name)) { - name = "_u"; - } - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - - // camelize (lower first character) the variable name - // pet_id => petId - name = camelize(name, true); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - @Override public String toModelName(final String name) { final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); - + // camelize the model name // phone_number => PhoneNumber final String camelizedName = camelize(sanitizedName); - + // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } - + // model name starts with number if (name.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); return modelName; } - + return camelizedName; } - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(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("/*", "/_*"); - } - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index b148a4da08f..cab432e5d17 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -5,25 +5,19 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; +public class ScalatraServerCodegen extends AbstractScalaCodegen implements CodegenConfig { + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; public ScalatraServerCodegen() { super(); @@ -42,7 +36,7 @@ public ScalatraServerCodegen() { "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") + "native", "super", "while", "type") ); defaultIncludes = new HashSet( @@ -93,17 +87,6 @@ public ScalatraServerCodegen() { supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); supportingFiles.add(new SupportingFile("sbt", "", "sbt")); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); @@ -121,9 +104,6 @@ public ScalatraServerCodegen() { importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime"); importMapping.put("LocalDate", "org.joda.time.LocalDate"); importMapping.put("LocalTime", "org.joda.time.LocalTime"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -141,71 +121,42 @@ public String getHelp() { return "Generates a Scala server application with Scalatra."; } - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - @Override public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); for (CodegenOperation op : operationList) { + // force http method to lower case op.httpMethod = op.httpMethod.toLowerCase(); - } - return objs; - } - + + String[] items = op.path.split("/", -1); + String scalaPath = ""; + int pathParamIndex = 0; + + for (int i = 0; i < items.length; ++i) { + if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} + scalaPath = scalaPath + ":" + items[i].replace("{", "").replace("}", ""); + pathParamIndex++; + } else { + scalaPath = scalaPath + items[i]; + } + + if (i != items.length -1) { + scalaPath = scalaPath + "/"; + } + } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + op.vendorExtensions.put("x-scalatra-path", scalaPath); } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); + return objs; } + @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java index 1a21b6609d8..6eb5beb9e61 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -30,6 +30,10 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege public SlimFrameworkServerCodegen() { super(); + // clear import mapping (from default generator) as slim does not use it + // at the moment + importMapping.clear(); + invokerPackage = camelize("SwaggerServer"); //String packagePath = "SwaggerServer"; 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 9a4ee3256ea..315e166f880 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 @@ -1,334 +1,402 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.*; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import org.apache.commons.lang3.BooleanUtils; - -import java.io.File; -import java.util.*; - -public class SpringCodegen extends AbstractJavaCodegen { - public static final String DEFAULT_LIBRARY = "spring-boot"; - public static final String CONFIG_PACKAGE = "configPackage"; - public static final String BASE_PACKAGE = "basePackage"; - public static final String INTERFACE_ONLY = "interfaceOnly"; - public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; - public static final String JAVA_8 = "java8"; - public static final String ASYNC = "async"; - protected String title = "Petstore Server"; - protected String configPackage = "io.swagger.configuration"; - protected String basePackage = "io.swagger"; - protected boolean interfaceOnly = false; - protected boolean singleContentTypes = false; - protected boolean java8 = false; - protected boolean async = false; - - public SpringCodegen() { - super(); - outputFolder = "generated-code/javaSpring"; - apiTestTemplateFiles.clear(); // TODO: add test template - embeddedTemplateDir = templateDir = "JavaSpring"; - apiPackage = "io.swagger.api"; - modelPackage = "io.swagger.model"; - invokerPackage = "io.swagger.api"; - artifactId = "swagger-spring-server"; - - additionalProperties.put("title", title); - additionalProperties.put(CONFIG_PACKAGE, configPackage); - additionalProperties.put(BASE_PACKAGE, basePackage); - - cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); - cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); - cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); - cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); - cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); - cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); - - supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); - supportedLibraries.put("spring-mvc", "Spring-MVC Server application using the SpringFox integration."); - setLibrary(DEFAULT_LIBRARY); - - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - library.setDefault(DEFAULT_LIBRARY); - library.setEnum(supportedLibraries); - library.setDefault(DEFAULT_LIBRARY); - cliOptions.add(library); - } - - @Override - public CodegenType getTag() { - return CodegenType.SERVER; - } - - @Override - public String getName() { - return "spring"; - } - - @Override - public String getHelp() { - return "Generates a Java SpringBoot Server application using the SpringFox integration."; - } - - @Override - public void processOpts() { - super.processOpts(); - - // clear model and api doc template as this codegen - // does not support auto-generated markdown doc at the moment - //TODO: add doc templates - modelDocTemplateFiles.remove("model_doc.mustache"); - apiDocTemplateFiles.remove("api_doc.mustache"); - - if (additionalProperties.containsKey(CONFIG_PACKAGE)) { - this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE)); - } - - if (additionalProperties.containsKey(BASE_PACKAGE)) { - this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); - } - - if (additionalProperties.containsKey(INTERFACE_ONLY)) { - this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); - } - - if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { - this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); - } - - if (additionalProperties.containsKey(JAVA_8)) { - this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString())); - } - - if (additionalProperties.containsKey(ASYNC)) { - this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString())); - } - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - - if (!this.interfaceOnly) { - apiTemplateFiles.put("apiController.mustache", "Controller.java"); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("notFoundException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); - if (library.equals(DEFAULT_LIBRARY)) { - supportingFiles.add(new SupportingFile("homeController.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); - supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", - (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); - supportingFiles.add(new SupportingFile("application.properties", - ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); - } - if (library.equals("spring-mvc")) { - supportingFiles.add(new SupportingFile("webApplication.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java")); - supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java")); - supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java")); - supportingFiles.add(new SupportingFile("application.properties", - ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); - } - } - - if (this.java8) { - additionalProperties.put("javaVersion", "1.8"); - typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "OffsetDateTime"); - importMapping.put("LocalDate", "java.time.LocalDate"); - importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); - } - } - - @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - String basePath = resourcePath; - if (basePath.startsWith("/")) { - basePath = basePath.substring(1); - } - int pos = basePath.indexOf("/"); - if (pos > 0) { - basePath = basePath.substring(0, pos); - } - - if (basePath == "") { - basePath = "default"; - } else { - co.subresourceOperation = !co.path.isEmpty(); - } - List opList = operations.get(basePath); - if (opList == null) { - opList = new ArrayList(); - operations.put(basePath, opList); - } - opList.add(co); - co.baseName = basePath; - } - - @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); - } - - String host = swagger.getHost(); - String port = "8080"; - if (host != null) { - String[] parts = host.split(":"); - if (parts.length > 1) { - port = parts[1]; - } - } - - this.additionalProperties.put("serverPort", port); - if (swagger != null && swagger.getPaths() != null) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for (Operation operation : path.getOperations()) { - if (operation.getTags() != null) { - List> tags = new ArrayList>(); - for (String tag : operation.getTags()) { - Map value = new HashMap(); - value.put("tag", tag); - value.put("hasMore", "true"); - tags.add(value); - } - if (tags.size() > 0) { - tags.get(tags.size() - 1).remove("hasMore"); - } - if (operation.getTags().size() > 0) { - String tag = operation.getTags().get(0); - operation.setTags(Arrays.asList(tag)); - } - operation.setVendorExtension("x-tags", tags); - } - } - } - } - } - } - - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - List responses = operation.responses; - if (responses != null) { - for (CodegenResponse resp : responses) { - if ("0".equals(resp.code)) { - resp.code = "200"; - } - } - } - - if (operation.returnType == null) { - operation.returnType = "Void"; - } else if (operation.returnType.startsWith("List")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if (end > 0) { - operation.returnType = rt.substring("List<".length(), end).trim(); - operation.returnContainer = "List"; - } - } else if (operation.returnType.startsWith("Map")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if (end > 0) { - operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); - operation.returnContainer = "Map"; - } - } else if (operation.returnType.startsWith("Set")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if (end > 0) { - operation.returnType = rt.substring("Set<".length(), end).trim(); - operation.returnContainer = "Set"; - } - } - } - } - - return objs; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - name = sanitizeName(name); - return camelize(name) + "Api"; - } - - public void setConfigPackage(String configPackage) { - this.configPackage = configPackage; - } - - public void setBasePackage(String configPackage) { - this.basePackage = configPackage; - } - - public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; } - - public void setSingleContentTypes(boolean singleContentTypes) { - this.singleContentTypes = singleContentTypes; - } - - public void setJava8(boolean java8) { this.java8 = java8; } - - public void setAsync(boolean async) { this.async = async; } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - super.postProcessModelProperty(model, property); - - if("null".equals(property.example)) { - property.example = null; - } - - //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { - model.imports.add("JsonProperty"); - - if(BooleanUtils.toBoolean(model.hasEnums)) { - model.imports.add("JsonValue"); - } - } - } - - @Override - public Map postProcessModelsEnum(Map objs) { - objs = super.postProcessModelsEnum(objs); - - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); - List models = (List) objs.get("models"); - for (Object _mo : models) { - Map mo = (Map) _mo; - CodegenModel cm = (CodegenModel) mo.get("model"); - // for enum model - if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { - cm.imports.add(importMapping.get("JsonValue")); - Map item = new HashMap(); - item.put("import", importMapping.get("JsonValue")); - imports.add(item); - } - } - - return objs; - } -} +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; + +import java.io.File; +import java.util.*; + +public class SpringCodegen extends AbstractJavaCodegen { + public static final String DEFAULT_LIBRARY = "spring-boot"; + public static final String TITLE = "title"; + public static final String CONFIG_PACKAGE = "configPackage"; + public static final String BASE_PACKAGE = "basePackage"; + public static final String INTERFACE_ONLY = "interfaceOnly"; + public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; + public static final String JAVA_8 = "java8"; + public static final String ASYNC = "async"; + public static final String SPRING_MVC_LIBRARY = "spring-mvc"; + public static final String SPRING_CLOUD_LIBRARY = "spring-cloud"; + + protected String title = "swagger-petstore"; + protected String configPackage = "io.swagger.configuration"; + protected String basePackage = "io.swagger"; + protected boolean interfaceOnly = false; + protected boolean singleContentTypes = false; + protected boolean java8 = false; + protected boolean async = false; + + public SpringCodegen() { + super(); + outputFolder = "generated-code/javaSpring"; + apiTestTemplateFiles.clear(); // TODO: add test template + embeddedTemplateDir = templateDir = "JavaSpring"; + apiPackage = "io.swagger.api"; + modelPackage = "io.swagger.model"; + invokerPackage = "io.swagger.api"; + artifactId = "swagger-spring"; + + additionalProperties.put(CONFIG_PACKAGE, configPackage); + additionalProperties.put(BASE_PACKAGE, basePackage); + + // spring uses the jackson lib + additionalProperties.put("jackson", "true"); + + cliOptions.add(new CliOption(TITLE, "server title name or client service name")); + cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); + cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); + cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); + cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); + cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); + cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); + + supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); + supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration."); + supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings."); + setLibrary(DEFAULT_LIBRARY); + + CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + library.setDefault(DEFAULT_LIBRARY); + library.setEnum(supportedLibraries); + library.setDefault(DEFAULT_LIBRARY); + cliOptions.add(library); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "spring"; + } + + @Override + public String getHelp() { + return "Generates a Java SpringBoot Server application using the SpringFox integration."; + } + + @Override + public void processOpts() { + super.processOpts(); + + // clear model and api doc template as this codegen + // does not support auto-generated markdown doc at the moment + //TODO: add doc templates + modelDocTemplateFiles.remove("model_doc.mustache"); + apiDocTemplateFiles.remove("api_doc.mustache"); + + if (additionalProperties.containsKey(TITLE)) { + this.setTitle((String) additionalProperties.get(TITLE)); + } + + if (additionalProperties.containsKey(CONFIG_PACKAGE)) { + this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE)); + } + + if (additionalProperties.containsKey(BASE_PACKAGE)) { + this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); + } + + if (additionalProperties.containsKey(INTERFACE_ONLY)) { + this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); + } + + if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { + this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); + } + + if (additionalProperties.containsKey(JAVA_8)) { + this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString())); + } + + if (additionalProperties.containsKey(ASYNC)) { + this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString())); + } + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + if (!this.interfaceOnly) { + if (library.equals(DEFAULT_LIBRARY)) { + supportingFiles.add(new SupportingFile("homeController.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); + supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", + (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java")); + supportingFiles.add(new SupportingFile("application.mustache", + ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); + } + if (library.equals(SPRING_MVC_LIBRARY)) { + supportingFiles.add(new SupportingFile("webApplication.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java")); + supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java")); + supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java")); + supportingFiles.add(new SupportingFile("application.properties", + ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); + } + if (library.equals(SPRING_CLOUD_LIBRARY)) { + supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java")); + supportingFiles.add(new SupportingFile("clientConfiguration.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java")); + apiTemplateFiles.put("apiClient.mustache", "Client.java"); + if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { + additionalProperties.put(SINGLE_CONTENT_TYPES, "true"); + this.setSingleContentTypes(true); + + } + + } else { + apiTemplateFiles.put("apiController.mustache", "Controller.java"); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("notFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); + } + } + + if (this.java8) { + additionalProperties.put("javaVersion", "1.8"); + typeMapping.put("date", "LocalDate"); + typeMapping.put("DateTime", "OffsetDateTime"); + importMapping.put("LocalDate", "java.time.LocalDate"); + importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); + } + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if (basePath.startsWith("/")) { + basePath = basePath.substring(1); + } + int pos = basePath.indexOf("/"); + if (pos > 0) { + basePath = basePath.substring(0, pos); + } + + if (basePath == "") { + basePath = "default"; + } else { + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; + } + + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); + if ("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } + + if(!additionalProperties.containsKey(TITLE)) { + // From the title, compute a reasonable name for the package and the API + String title = swagger.getInfo().getTitle(); + + // Drop any API suffix + if (title != null) { + title = title.trim().replace(" ", "-"); + if (title.toUpperCase().endsWith("API")) { + title = title.substring(0, title.length() - 3); + } + + this.title = camelize(sanitizeName(title), true); + } + additionalProperties.put(TITLE, this.title); + } + + String host = swagger.getHost(); + String port = "8080"; + if (host != null) { + String[] parts = host.split(":"); + if (parts.length > 1) { + port = parts[1]; + } + } + + this.additionalProperties.put("serverPort", port); + if (swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + if (operation.getTags() != null) { + List> tags = new ArrayList>(); + for (String tag : operation.getTags()) { + Map value = new HashMap(); + value.put("tag", tag); + value.put("hasMore", "true"); + tags.add(value); + } + if (tags.size() > 0) { + tags.get(tags.size() - 1).remove("hasMore"); + } + if (operation.getTags().size() > 0) { + String tag = operation.getTags().get(0); + operation.setTags(Arrays.asList(tag)); + } + operation.setVendorExtension("x-tags", tags); + } + } + } + } + } + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + List responses = operation.responses; + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { + resp.code = "200"; + } + } + } + + if (operation.returnType == null) { + operation.returnType = "Void"; + } else if (operation.returnType.startsWith("List")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("List<".length(), end).trim(); + operation.returnContainer = "List"; + } + } else if (operation.returnType.startsWith("Map")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); + operation.returnContainer = "Map"; + } + } else if (operation.returnType.startsWith("Set")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Set<".length(), end).trim(); + operation.returnContainer = "Set"; + } + } + } + } + + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + if(library.equals(SPRING_CLOUD_LIBRARY)) { + List authMethods = (List) objs.get("authMethods"); + if (authMethods != null) { + for (CodegenSecurity authMethod : authMethods) { + authMethod.name = camelize(sanitizeName(authMethod.name), true); + } + } + } + return objs; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + name = sanitizeName(name); + return camelize(name) + "Api"; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setConfigPackage(String configPackage) { + this.configPackage = configPackage; + } + + public void setBasePackage(String configPackage) { + this.basePackage = configPackage; + } + + public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; } + + public void setSingleContentTypes(boolean singleContentTypes) { + this.singleContentTypes = singleContentTypes; + } + + public void setJava8(boolean java8) { this.java8 = java8; } + + public void setAsync(boolean async) { this.async = async; } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + if ("null".equals(property.example)) { + property.example = null; + } + + //Add imports for Jackson + if (!Boolean.TRUE.equals(model.isEnum)) { + model.imports.add("JsonProperty"); + + if (Boolean.TRUE.equals(model.hasEnums)) { + model.imports.add("JsonValue"); + } + } else { // enum class + //Needed imports for Jackson's JsonCreator + if (additionalProperties.containsKey("jackson")) { + model.imports.add("JsonCreator"); + } + } + } + + @Override + public Map postProcessModelsEnum(Map objs) { + objs = super.postProcessModelsEnum(objs); + + //Add imports for Jackson + List> imports = (List>)objs.get("imports"); + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + // for enum model + if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { + cm.imports.add(importMapping.get("JsonValue")); + Map item = new HashMap(); + item.put("import", importMapping.get("JsonValue")); + imports.add(item); + } + } + + return objs; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index c64fcfb04ef..4251db48bbb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -18,6 +18,11 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { public StaticDocCodegen() { super(); + + // clear import mapping (from default generator) as this generator does not use it + // at the moment + importMapping.clear(); + outputFolder = "docs"; modelTemplateFiles.put("model.mustache", ".html"); apiTemplateFiles.put("operation.mustache", ".html"); @@ -85,4 +90,16 @@ public String apiFileFolder() { public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + "models"; } + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java new file mode 100644 index 00000000000..1979d0c1913 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -0,0 +1,164 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public StaticHtml2Generator() { + super(); + outputFolder = "docs"; + embeddedTemplateDir = templateDir = "htmlDocs2"; + + defaultIncludes = new HashSet(); + + cliOptions.add(new CliOption("appName", "short name of the application")); + cliOptions.add(new CliOption("appDescription", "description of the application")); + cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); + cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); + + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "https://helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); + reservedWords = new HashSet(); + + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap(); + } + + @Override + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + @Override + public String getName() { + return "html2"; + } + + @Override + public String getHelp() { + return "Generates a static HTML file."; + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } + + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + if (op.returnType != null) { + op.returnType = normalizeType(op.returnType); + } + + //path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' + op.path = sanitizePath(op.path); + + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required != null && p.required) { + lastRequired = p; + } else { + lastOptional = p; + } + } + for (CodegenParameter p : op.allParams) { + if (p == lastRequired) { + p.vendorExtensions.put("x-codegen-hasMoreRequired", false); + } else if (p == lastOptional) { + p.vendorExtensions.put("x-codegen-hasMoreOptional", false); + } else { + p.vendorExtensions.put("x-codegen-hasMoreRequired", true); + p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + } + } + op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); + + return op; + } + + + private String sanitizePath(String p) { + //prefer replace a ', instead of a fuLL URL encode for readability + return p.replaceAll("'", "%27"); + } + + /** + * Normalize type by wrapping primitive types with single quotes. + * + * @param type Primitive type + * @return Normalized type + */ + public String normalizeType(String type) { + return type.replaceAll("\\b(Boolean|Integer|Number|String|Date)\\b", "'$1'"); + } + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 0db05d5bc0a..541bf98e6ad 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -19,12 +19,10 @@ import java.util.Map; public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { - private static final String ALL_OPERATIONS = ""; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; public StaticHtmlGenerator() { super(); @@ -101,4 +99,17 @@ public Map postProcessOperations(Map objs) { } return objs; } + + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index 48f0197068b..9faa3041968 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -1,27 +1,28 @@ package io.swagger.codegen.languages; -import java.io.File; - +import io.swagger.codegen.*; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.Swagger; -import io.swagger.util.Yaml; +import java.io.File; public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { - + public static final String OUTPUT_NAME = "outputFile"; + private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerYamlGenerator.class); + protected String outputFile = "swagger.yaml"; + public SwaggerYamlGenerator() { super(); embeddedTemplateDir = templateDir = "swagger"; outputFolder = "generated-code/swagger"; + cliOptions.add(new CliOption(OUTPUT_NAME, "output filename")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); } @@ -40,11 +41,20 @@ public String getHelp() { return "Creates a static swagger.yaml file."; } + + @Override + public void processOpts() { + super.processOpts(); + if(additionalProperties.containsKey(OUTPUT_NAME)) { + this.outputFile = additionalProperties.get(OUTPUT_NAME).toString(); + } + } + @Override public void processSwagger(Swagger swagger) { try { String swaggerString = Yaml.mapper().writeValueAsString(swagger); - String outputFile = outputFolder + File.separator + "swagger.yaml"; + String outputFile = outputFolder + File.separator + this.outputFile; FileUtils.writeStringToFile(new File(outputFile), swaggerString); LOGGER.debug("wrote file to " + outputFile); } catch (Exception e) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index f23cf72d502..b9595c163a6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -38,8 +38,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { public static final String POD_SCREENSHOTS = "podScreenshots"; public static final String POD_DOCUMENTATION_URL = "podDocumentationURL"; public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace"; + public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen"; protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; - protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT }; + protected static final String LIBRARY_RX_SWIFT = "RxSwift"; + protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT }; protected String projectName = "SwaggerClient"; protected boolean unwrapRequired; protected boolean swiftUseApiNamespace; @@ -86,8 +88,10 @@ public SwiftCodegen() { ); defaultIncludes = new HashSet( Arrays.asList( + "NSData", "NSDate", "NSURL", // for file + "NSUUID", "Array", "Dictionary", "Set", @@ -127,10 +131,9 @@ public SwiftCodegen() { typeMapping.put("double", "Double"); typeMapping.put("object", "AnyObject"); typeMapping.put("file", "NSURL"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "String"); - typeMapping.put("ByteArray", "String"); + typeMapping.put("binary", "NSData"); + typeMapping.put("ByteArray", "NSData"); + typeMapping.put("UUID", "NSUUID"); importMapping = new HashMap(); @@ -151,11 +154,21 @@ public SwiftCodegen() { cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } @Override public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } // Setup project name if (additionalProperties.containsKey(PROJECT_NAME)) { @@ -184,6 +197,9 @@ public void processOpts() { if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) { additionalProperties.put("usePromiseKit", true); } + if (ArrayUtils.contains(responseAs, LIBRARY_RX_SWIFT)) { + additionalProperties.put("useRxSwift", true); + } // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { @@ -191,6 +207,10 @@ public void processOpts() { } additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace); + if (!additionalProperties.containsKey(POD_AUTHORS)) { + additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS); + } + supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); @@ -251,6 +271,11 @@ public String getSwaggerType(Property p) { return toModelName(type); } + @Override + public boolean isDataTypeBinary(final String dataType) { + return dataType != null && dataType.equals("NSData"); + } + /** * Output the proper model name (capitalized) * @@ -336,10 +361,10 @@ public CodegenProperty fromProperty(String name, Property p) { List> swiftEnums = new ArrayList>(); List values = (List) codegenProperty.allowableValues.get("values"); - for (String value : values) { + for (Object value : values) { Map map = new HashMap(); - map.put("enum", toSwiftyEnumName(value)); - map.put("raw", value); + map.put("enum", toSwiftyEnumName(String.valueOf(value))); + map.put("raw", String.valueOf(value)); swiftEnums.add(map); } codegenProperty.allowableValues.put("values", swiftEnums); @@ -359,12 +384,20 @@ public CodegenProperty fromProperty(String name, Property p) { @SuppressWarnings("static-method") public String toSwiftyEnumName(String value) { + if (value.matches("^-?\\d*\\.{0,1}\\d+.*")) { // starts with number + value = "Number" + value; + value = value.replaceAll("-", "Minus"); + value = value.replaceAll("\\+", "Plus"); + value = value.replaceAll("\\.", "Dot"); + } + // Prevent from breaking properly cased identifier if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { return value; } - char[] separators = {'-', '_', ' ', ':'}; - return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", ""); + + char[] separators = {'-', '_', ' ', ':', '/'}; + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :/]", ""); } @@ -513,7 +546,7 @@ public String toEnumVarName(String name, String datatype) { // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value)); // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index c9dd10b2a58..aeb5d774add 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -3,10 +3,13 @@ import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.List; +import java.util.Map; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.SupportingFile; import io.swagger.models.ModelImpl; import io.swagger.models.properties.ArrayProperty; @@ -68,6 +71,8 @@ public void processOpts() { supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); + supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts")); + supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -162,6 +167,46 @@ public void postProcessParameter(CodegenParameter parameter) { parameter.dataType = addModelPrefix(parameter.dataType); } + @Override + public Map postProcessOperations(Map operations) { + Map objs = (Map) operations.get("operations"); + List ops = (List) objs.get("operation"); + for (CodegenOperation op : ops) { + // Convert httpMethod to Angular's RequestMethod enum + // https://angular.io/docs/ts/latest/api/http/index/RequestMethod-enum.html + switch (op.httpMethod) { + case "GET": + op.httpMethod = "RequestMethod.Get"; + break; + case "POST": + op.httpMethod = "RequestMethod.Post"; + break; + case "PUT": + op.httpMethod = "RequestMethod.Put"; + break; + case "DELETE": + op.httpMethod = "RequestMethod.Delete"; + break; + case "OPTIONS": + op.httpMethod = "RequestMethod.Options"; + break; + case "HEAD": + op.httpMethod = "RequestMethod.Head"; + break; + case "PATCH": + op.httpMethod = "RequestMethod.Patch"; + break; + default: + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + } + + // Convert path to TypeScript template string + op.path = op.path.replaceAll("\\{(.*?)\\}", "\\$\\{$1\\}"); + } + + return operations; + } + public String getNpmName() { return npmName; } 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 cf25259e61c..edde98f3e8d 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 @@ -1,9 +1,14 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.SupportingFile; import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen { @@ -15,6 +20,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public TypeScriptFetchClientCodegen() { super(); + + // clear import mapping (from default generator) as TS does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code/typescript-fetch"; embeddedTemplateDir = templateDir = "TypeScript-Fetch"; this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); @@ -67,4 +77,24 @@ public void setNpmVersion(String npmVersion) { this.npmVersion = npmVersion; } + @Override + public Map postProcessModels(Map objs) { + // process enum in models + List models = (List) postProcessModelsEnum(objs).get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + cm.imports = new TreeSet(cm.imports); + for (CodegenProperty var : cm.vars) { + // name enum with model name, e.g. StatuEnum => PetStatusEnum + if (Boolean.TRUE.equals(var.isEnum)) { + var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName); + var.enumName = cm.classname + var.enumName; + } + } + } + + return objs; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index db9e2fcf2ad..67a6ed0b422 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -26,6 +26,11 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen public TypeScriptNodeClientCodegen() { super(); + + // clear import mapping (from default generator) as TS does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code/typescript-node"; embeddedTemplateDir = templateDir = "typescript-node"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java new file mode 100644 index 00000000000..b212e42a316 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java @@ -0,0 +1,219 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.util.Json; +import io.swagger.util.Yaml; +import org.apache.commons.lang3.BooleanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.*; + +public class UndertowCodegen extends AbstractJavaCodegen { + + private static final Logger LOGGER = LoggerFactory.getLogger(UndertowCodegen.class); + + protected String title = "Swagger Undertow Server"; + protected String implFolder = "src/main/java"; + public UndertowCodegen() { + super(); + + sourceFolder = "src/main/java"; + apiTestTemplateFiles.clear(); // TODO: add test template + embeddedTemplateDir = templateDir = "undertow"; + invokerPackage = "io.swagger.handler"; + artifactId = "swagger-undertow-server"; + dateLibrary = "legacy"; //TODO: add joda support + + // clear model and api doc template as this codegen + // does not support auto-generated markdown doc at the moment + //TODO: add doc templates + modelDocTemplateFiles.remove("model_doc.mustache"); + apiDocTemplateFiles.remove("api_doc.mustache"); + + + apiPackage = System.getProperty("swagger.codegen.undertow.apipackage", "io.swagger.handler"); + modelPackage = System.getProperty("swagger.codegen.undertow.modelpackage", "io.swagger.model"); + + additionalProperties.put("title", title); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "undertow"; + } + + @Override + public String getHelp() { + return "Generates a Java Undertow Server application."; + } + + @Override + public void processOpts() { + super.processOpts(); + + apiTemplateFiles.remove("api.mustache"); + + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); + + // keep the yaml in config folder for framework validation. + supportingFiles.add(new SupportingFile("swagger.mustache", ("src.main.resources.config").replace(".", java.io.File.separator), "swagger.json")); + supportingFiles.add(new SupportingFile("handler.mustache", ("src.main.java.io.swagger.handler").replace(".", java.io.File.separator), "PathHandlerProvider.java")); + supportingFiles.add(new SupportingFile("service.mustache", ("src.main.resources.META-INF.services").replace(".", java.io.File.separator), "com.networknt.server.HandlerProvider")); + + // configuration files + supportingFiles.add(new SupportingFile("server.json", ("src.main.resources.config").replace(".", java.io.File.separator), "server.json")); + supportingFiles.add(new SupportingFile("security.json", ("src.main.resources.config").replace(".", java.io.File.separator), "security.json")); + supportingFiles.add(new SupportingFile("primary.crt", ("src.main.resources.config.oauth").replace(".", java.io.File.separator), "primary.crt")); + + } + + /* + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if (basePath.startsWith("/")) { + basePath = basePath.substring(1); + } + int pos = basePath.indexOf("/"); + if (pos > 0) { + basePath = basePath.substring(0, pos); + } + + if (basePath == "") { + basePath = "default"; + } else { + if (co.path.startsWith("/" + basePath)) { + co.path = co.path.substring(("/" + basePath).length()); + } + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; + } + */ + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.returnType == null) { + operation.returnType = "Void"; + } else if (operation.returnType.startsWith("List")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("List<".length(), end); + operation.returnContainer = "List"; + } + } else if (operation.returnType.startsWith("Map")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Map<".length(), end); + operation.returnContainer = "Map"; + } + } else if (operation.returnType.startsWith("Set")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Set<".length(), end); + operation.returnContainer = "Set"; + } + } + } + } + return objs; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + //Add imports for Jackson + if(!BooleanUtils.toBoolean(model.isEnum)) { + model.imports.add("JsonProperty"); + + if(BooleanUtils.toBoolean(model.hasEnums)) { + model.imports.add("JsonValue"); + } + } + } + + @Override + public Map postProcessModelsEnum(Map objs) { + objs = super.postProcessModelsEnum(objs); + + //Add imports for Jackson + List> imports = (List>)objs.get("imports"); + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + // for enum model + if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { + cm.imports.add(importMapping.get("JsonValue")); + Map item = new HashMap(); + item.put("import", importMapping.get("JsonValue")); + imports.add(item); + } + } + + return objs; + } + + public String apiFilename(String templateName, String tag) { + String result = super.apiFilename(templateName, tag); + + if ( templateName.endsWith("api.mustache") ) { + int ix = result.indexOf(sourceFolder); + String beg = result.substring(0, ix); + String end = result.substring(ix + sourceFolder.length()); + new java.io.File(beg + implFolder).mkdirs(); + result = beg + implFolder + end; + } + return result; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + System.out.println("swagger" + swagger.toString()); + if(swagger != null) { + try { + //objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); + objs.put("swagger-json", Json.pretty().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + return super.postProcessSupportingFileData(objs); + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultHandler"; + } + name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + return camelize(name)+ "Handler"; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JMeter/api.mustache b/modules/swagger-codegen/src/main/resources/JMeter/api.mustache index b52f7f3b97c..f0c67670e5d 100644 --- a/modules/swagger-codegen/src/main/resources/JMeter/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JMeter/api.mustache @@ -26,7 +26,7 @@ testCases - ${__P(host,10)} + ${__P(testCases,10)} = @@ -90,7 +90,7 @@ {{#queryParams}} false - 0 + {{=<% %>=}}${<% paramName %>}<%={{ }}=%> = true {{paramName}} diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 5f5376f2861..c34dd51dcea 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import com.fasterxml.jackson.annotation.*; @@ -39,7 +40,6 @@ import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; @@ -71,7 +71,7 @@ public class ApiClient { objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); {{#java8}} - objectMapper.registerModule(new JSR310Module()); + objectMapper.registerModule(new JavaTimeModule()); {{/java8}} {{^java8}} objectMapper.registerModule(new JodaModule()); @@ -95,12 +95,7 @@ public class ApiClient { } public static DateFormat buildDefaultDateFormat() { - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - // Use UTC as the default time zone. - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; + return new RFC3339DateFormat(); } /** @@ -496,9 +491,16 @@ public class ApiClient { if (contentType.startsWith("multipart/form-data")) { FormDataMultiPart mp = new FormDataMultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { + if( param.getValue() instanceof List && !( ( List ) param.getValue() ).isEmpty() + && ( ( List ) param.getValue() ).get( 0 ) instanceof File ) { + @SuppressWarnings( "unchecked" ) + List files = ( List ) param.getValue(); + for( File file : files ) { + mp.bodyPart( new FileDataBodyPart( param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE ) ); + } + } else if (param.getValue() instanceof File) { File file = (File) param.getValue(); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); } else { mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); } @@ -607,7 +609,7 @@ public class ApiClient { statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (returnType == null) diff --git a/modules/swagger-codegen/src/main/resources/Java/README.mustache b/modules/swagger-codegen/src/main/resources/Java/README.mustache index f3b766a67d8..17d2a93d43c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/README.mustache @@ -60,7 +60,7 @@ Please follow the [installation](#installation) instruction and execute the foll {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} import {{{invokerPackage}}}.*; import {{{invokerPackage}}}.auth.*; -import {{{invokerPackage}}}.model.*; +import {{{modelPackage}}}.*; import {{{package}}}.{{{classname}}}; import java.io.File; @@ -140,7 +140,7 @@ Class | Method | HTTP request | Description ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..16fd2a495a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache @@ -0,0 +1,21 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +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/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 4d54d84d337..80db47354d0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; import com.sun.jersey.api.client.GenericType; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index f73a6f5b3f8..5af060f1173 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -55,9 +55,9 @@ public class ApiKeyAuth implements Authentication { } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache new file mode 100644 index 00000000000..f9a3265fbb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache @@ -0,0 +1,27 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache index 9920a371e5d..c969c9f7b08 100644 --- a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache @@ -32,8 +32,14 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 23 } 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 @@ -77,9 +83,15 @@ if(hasProperty('target') && target == 'android') { 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 { @@ -95,9 +107,9 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "1.19.1" - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" junit_version = "4.12" } @@ -109,8 +121,13 @@ dependencies { 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.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + {{#java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + {{/java8}} + {{^java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" compile "joda-time:joda-time:$jodatime_version" + {{/java8}} compile "com.brsanthu:migbase64:2.2" testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/build.sbt.mustache new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache index 72d362dafd8..5f192121eb4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 15ce7431551..5641afe195f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -136,6 +136,7 @@ public class ApiClient { objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.setDateFormat(new RFC3339DateFormat()); {{^java8}} objectMapper.registerModule(new JodaModule()); {{/java8}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache index 822aad582d4..baf29b5f4de 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache @@ -8,7 +8,6 @@ import java.nio.charset.Charset; import java.util.*; import java.text.DateFormat; -import java.text.SimpleDateFormat; import feign.codec.EncodeException; import feign.codec.Encoder; @@ -32,12 +31,8 @@ public class FormAwareEncoder implements Encoder { public FormAwareEncoder(Encoder delegate) { this.delegate = delegate; - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + this.dateFormat = new RFC3339DateFormat();; - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); this.boundaryBytes = BOUNDARY.getBytes(UTF_8); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache index 50e2cf3fbe9..56560172ee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache @@ -34,7 +34,7 @@ After the client library is installed/deployed, you can use it in your Maven pro ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index c9d756d33ec..6cb2deaccbc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -27,7 +27,7 @@ public interface {{classname}} extends ApiClient.Api { @Headers({ "Content-type: {{vendorExtensions.x-contentType}}", "Accept: {{vendorExtensions.x-accepts}}",{{#headerParams}} - "{{paramName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, + "{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, {{/hasMore}}{{/headerParams}} }) {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}@Param("{{paramName}}") {{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache index 371b24dbe55..9982cd7fc49 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache @@ -32,10 +32,10 @@ public class ApiKeyAuth implements RequestInterceptor { @Override public void apply(RequestTemplate template) { - if (location == "query") { + if ("query".equals(location)) { template.query(paramName, apiKey); - } else if (location == "header") { + } else if ("header".equals(location)) { template.header(paramName, apiKey); } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache index e1df11443b7..adbe4800eb9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache @@ -94,9 +94,9 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.8" + swagger_annotations_version = "1.5.9" jackson_version = "2.7.5" - feign_version = "8.16.0" + feign_version = "8.17.0" junit_version = "4.12" oltu_version = "1.0.1" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache index f26bd27f1e8..98450123af6 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -9,9 +9,9 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.9" % "compile", "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", - "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile", diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 36cde285499..027ae8a9fc4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -95,6 +95,11 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -160,8 +165,8 @@ {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} ${java.version} ${java.version} - 1.5.8 - 8.16.0 + 1.5.9 + 8.17.0 2.7.5 4.12 1.0.0 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 517b6e1c8aa..db0daf0d3f4 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 @@ -39,7 +39,6 @@ import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -70,14 +69,7 @@ public class ApiClient { json = new JSON(); httpClient = buildHttpClient(debugging); - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.dateFormat = new RFC3339DateFormat(); // Set default User-Agent. setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); @@ -498,8 +490,15 @@ public class ApiClient { * Deserialize response body to Java object according to the Content-Type. */ public T deserialize(Response response, GenericType returnType) throws ApiException { - // Handle file downloading. - if (returnType.equals(File.class)) { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.equals(File.class)) { + // Handle file downloading. @SuppressWarnings("unchecked") T file = (T) downloadFileFromResponse(response); return file; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache index 7d9a9732862..ec15354a8a6 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -24,8 +24,9 @@ public class JSON implements ContextResolver { mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); {{#java8}} - mapper.registerModule(new JSR310Module()); + mapper.registerModule(new JavaTimeModule()); {{/java8}} {{^java8}} mapper.registerModule(new JodaModule()); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache index b17cd34e420..285b35a32a4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache @@ -106,10 +106,10 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "2.22.2" {{^java8}} - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" {{/java8}} junit_version = "4.12" } @@ -118,7 +118,7 @@ dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.glassfish.jersey.core:jersey-client:$jersey_version" compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" @@ -126,7 +126,7 @@ dependencies { compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" {{/java8}} {{^java8}} - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" compile "joda-time:joda-time:$jodatime_version" {{/java8}} compile "com.brsanthu:migbase64:2.2" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache index 46ff84d1e72..c43d6a0375c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache @@ -12,16 +12,16 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.8", "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", {{#java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.0", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", {{/java8}} {{^java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", - "joda-time" % "joda-time" % "2.9.3", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", + "joda-time" % "joda-time" % "2.9.4", {{/java8}} "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache index d6b51a2f884..ac42568cee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -98,7 +98,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 2.5.1 {{#java8}} 1.8 @@ -110,6 +110,11 @@ {{/java8}} + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -133,7 +138,7 @@ org.glassfish.jersey.media jersey-media-json-jackson - 2.22.1 + ${jersey-version} @@ -163,7 +168,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -188,11 +193,11 @@ - 1.5.8 + 1.5.9 2.22.2 - 2.7.0 + 2.7.5 {{^java8}} - 2.9.3 + 2.9.4 {{/java8}} 1.0.0 4.12 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 3712dcd7224..9c75d671607 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 @@ -790,6 +790,7 @@ public class ApiClient { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -984,6 +985,7 @@ public class ApiClient { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache index 82c86b3e215..3909393697c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache @@ -8,7 +8,7 @@ import java.util.Map; /** * API response returned by API call. * - * @param T The type of data that is deserialized from response body + * @param The type of data that is deserialized from response body */ public class ApiResponse { final private int statusCode; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 4cb2a34ab20..06f26da304b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -89,9 +89,10 @@ public class JSON { * * @param Type * @param body The JSON string - * @param returnType The type to deserialize inot + * @param returnType The type to deserialize into * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { @@ -150,10 +151,9 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { * * @param json Json element * @param date Type - * @param typeOfSrc Type * @param context Json Serialization Context * @return Date - * @throw JsonParseException if fail to parse + * @throws JsonParseException if fail to parse */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { @@ -287,4 +287,4 @@ class LocalDateTypeAdapter extends TypeAdapter { } } } -{{/java8}} \ No newline at end of file +{{/java8}} 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 7abe897d42e..4f991f21936 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 @@ -58,7 +58,7 @@ public class {{classname}} { {{/required}}{{/allParams}} // create path and map variables - String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index 2d6ca9c29d6..698c1a97f94 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -96,6 +96,11 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -126,6 +131,15 @@ ${jodatime-version} {{/java8}} + {{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + + {{/useBeanValidation}} @@ -147,4 +161,4 @@ 4.12 UTF-8 - + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache index 50e2cf3fbe9..56560172ee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache @@ -34,7 +34,7 @@ After the client library is installed/deployed, you can use it in your Maven pro ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index aa84768b47a..e03801db6c2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -27,7 +27,7 @@ public interface {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} @@ -41,7 +41,7 @@ public interface {{classname}} { * @return void */ {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") void {{operationId}}( {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache index fec45262e93..f6a86f22ab4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache @@ -40,7 +40,7 @@ public class ApiKeyAuth implements Interceptor { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public class ApiKeyAuth implements Interceptor { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache index f8788583db5..81de324b691 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@retrofit.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache index be9a3ca9b26..f1f9027ae51 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache index 29206e1546b..5d6da4a9437 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@retrofit.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache index 8a8bdc74c88..7b8be8442e0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@retrofit.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache index c9991c230e5..c816526cd59 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -104,6 +104,11 @@ 1.7 + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -142,7 +147,7 @@ - 1.5.8 + 1.5.9 1.9.0 2.7.5 2.9.3 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache index 3c5b1bb7e69..2a580ab34ec 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@retrofit.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index 9afdc5488b5..f9434978704 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -74,7 +74,7 @@ public class ApiClient { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -82,8 +82,8 @@ public class ApiClient { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -92,9 +92,9 @@ public class ApiClient { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -103,11 +103,11 @@ public class ApiClient { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client Secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -154,7 +154,7 @@ public class ApiClient { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -168,8 +168,8 @@ public class ApiClient { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -188,7 +188,7 @@ public class ApiClient { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -202,7 +202,7 @@ public class ApiClient { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -216,7 +216,7 @@ public class ApiClient { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -230,9 +230,9 @@ public class ApiClient { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -252,7 +252,7 @@ public class ApiClient { /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -266,8 +266,8 @@ public class ApiClient { /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization interceptor */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -305,7 +305,7 @@ public class ApiClient { /** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit - * @param okClient + * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 9bd835a4a36..7682d27c9c8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -25,10 +25,10 @@ public interface {{classname}} { * {{summary}} * {{notes}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> +{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> */ {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache index 92c0df0ddea..2f4bae3dd02 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache @@ -40,7 +40,7 @@ public class ApiKeyAuth implements Interceptor { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.url().uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public class ApiKeyAuth implements Interceptor { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache index f8788583db5..97b03fcb717 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@retrofit2.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache index 8d9208978b5..2e237383ee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}\"") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save new file mode 100644 index 00000000000..a203e99a223 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{#isMultipart}}retrofit.http@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache index 29206e1546b..c7748f3bf27 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@retrofit2.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache index 8a8bdc74c88..8fe7c380c41 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@retrofit2.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index a3e28ff4595..cacb10ef9e7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -95,6 +96,11 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -152,6 +158,7 @@ + UTF-8 {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} ${java.version} ${java.version} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache index 3c5b1bb7e69..abb87510ecf 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@retrofit2.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache index 861d97234cf..26b9876c7e1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache @@ -1,4 +1,4 @@ -/** +/* * {{{appName}}} * {{{appDescription}}} * diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 1143fc413df..c697b32ff7a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -6,8 +6,17 @@ import java.util.Objects; {{#imports}} import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#parcelableModel}} +import android.os.Parcelable; +import android.os.Parcel; +{{/parcelableModel}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} -{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#models}} {{#model}} {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/Java/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/modelEnum.mustache index 679ffbacb50..baddbae19be 100644 --- a/modules/swagger-codegen/src/main/resources/Java/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/modelEnum.mustache @@ -1,3 +1,7 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + /** * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} */ @@ -24,4 +28,16 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum public String toString() { return String.valueOf(value); } +{{#jackson}} + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +{{/jackson}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/modelInnerEnum.mustache index 398dae3e77f..160dfc09259 100644 --- a/modules/swagger-codegen/src/main/resources/Java/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/modelInnerEnum.mustache @@ -30,4 +30,16 @@ public String toString() { return String.valueOf(value); } +{{#jackson}} + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +{{/jackson}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 4cebdb967ab..67ef6032609 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -3,7 +3,7 @@ */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { +public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcelableModel}}implements Parcelable {{#serializableModel}}, Serializable {{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable {{/serializableModel}}{{/parcelableModel}}{ {{#vars}} {{#isEnum}} {{^isContainer}} @@ -32,6 +32,20 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali this.{{name}} = {{name}}; return this; } + {{#isListContainer}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isListContainer}} + {{#isMapContainer}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMapContainer}} {{/isReadOnly}} /** @@ -50,9 +64,12 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} - @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} +{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } @@ -105,4 +122,46 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali } return o.toString().replace("\n", "\n "); } + + {{#parcelableModel}} + public void writeToParcel(Parcel out, int flags) { + {{#parent}} super.writeToParcel(out, flags); {{/parent}} {{#vars}} + out.writeValue({{name}}); + {{/vars}} + } + + public {{classname}}() { + super(); + } + + {{classname}}(Parcel in) { + {{#parent}} super(in); {{/parent}} + {{#vars}} + {{#isContainer}} + {{#complexType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); + {{/complexType}} + {{^complexType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); + {{/complexType}} + {{/isContainer}} + {{^isContainer}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); + {{/isContainer}} + {{/vars}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { + return new {{classname}}(in); + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; + {{/parcelableModel}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 3a8c440eaee..a5392522568 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -107,6 +107,11 @@ {{/java8}} + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -160,7 +165,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -175,7 +180,15 @@ migbase64 2.2 - +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} junit @@ -188,9 +201,9 @@ UTF-8 1.5.8 1.19.1 - 2.7.0 + 2.7.5 {{^java8}} - 2.9.3 + 2.9.4 {{/java8}} 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache index 0a5e225306c..71056d37509 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache @@ -18,7 +18,7 @@ import {{modelPackage}}.*; public class {{classname}} { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache index 6010e26704f..c5c3143cb94 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache @@ -1,17 +1,44 @@ + /** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ + public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}} + {{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}} + {{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/gson}} - public enum {{{datatypeWithEnum}}} { - {{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + private {{{datatype}}} value; - private String value; - - {{{datatypeWithEnum}}}(String value) { + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{datatype}}} value) { this.value = value; } @Override @JsonValue public String toString() { - return value; + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; } } diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache index 7aea7b92f22..76c2cbf5a76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache @@ -1,3 +1,42 @@ -public enum {{classname}} { - {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}} -} \ No newline at end of file +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache index 58bfed16381..f736844264b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache @@ -1,13 +1,28 @@ {{#description}}@ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} - -{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} - -{{>enumClass}}{{/items}}{{/items.isEnum}} - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{/items}} + {{/items.isEnum}} + {{#jackson}} + @JsonProperty("{{baseName}}") + {{/jackson}} + {{#gson}} + @SerializedName("{{baseName}}") + {{/gson}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} {{#vars}} /**{{#description}} * {{{description}}}{{/description}}{{#minimum}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index a46b1960a67..5b6b7c0161d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -111,7 +111,7 @@ 1.0.0 - 1.0.4 + 1.0.8 9.2.9.v20150224 1.0.1 4.8.2 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..061e000f5a2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache @@ -0,0 +1,19 @@ +package {{apiPackage}}; + +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/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index e1eb66091ae..59b71d2ba47 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -5,6 +5,7 @@ import {{package}}.{{classname}}Service; import {{package}}.factories.{{classname}}ServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; {{#imports}}import {{import}}; {{/imports}} @@ -48,7 +49,7 @@ public class {{classname}} { {{/hasMore}}{{/responses}} }) public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext) throws NotFoundException { - return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext); + return delegate.{{nickname}}({{#allParams}}{{#isFile}}{{paramName}}InputStream, {{paramName}}Detail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext); } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache new file mode 100644 index 00000000000..a48256d027a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache @@ -0,0 +1 @@ +{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache new file mode 100644 index 00000000000..5fabe593164 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache @@ -0,0 +1,55 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import {{package}}.{{classname}}Service; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; + +import io.swagger.annotations.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.List; + +@Path("/{{baseName}}") +@RequestScoped + +@Api(description = "the {{baseName}} API") +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +{{>generatedAnnotation}} + +public class {{classname}} { + + @Context SecurityContext securityContext; + + @Inject {{classname}}Service delegate; + +{{#operations}} +{{#operation}} + + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}},{{/hasMore}}{{/responses}} }) + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}, {{/allParams}}securityContext); + } +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache new file mode 100644 index 00000000000..64eb6e38adb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache @@ -0,0 +1,25 @@ +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +{{>generatedAnnotation}} +{{#operations}} +public interface {{classname}}Service { + {{#operation}} + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext); + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache new file mode 100644 index 00000000000..bce7fe5e930 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache @@ -0,0 +1,31 @@ +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl implements {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache new file mode 100644 index 00000000000..2b28441d3d0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache new file mode 100644 index 00000000000..1ef4a61efbe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache @@ -0,0 +1,16 @@ +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + +@XmlType(name="{{classname}}") +@XmlEnum +public enum {{classname}} { + {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/allowableValues}} + + public String value() { + return name(); + } + + public static {{classname}} fromValue(String v) { + return valueOf(v); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache new file mode 100644 index 00000000000..3bc0dfe132b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache new file mode 100644 index 00000000000..1360d796826 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache new file mode 100644 index 00000000000..2c383a41a28 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache @@ -0,0 +1,14 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +{{#models}} +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +{{#isEnum}}{{>enumClass}}{{/isEnum}} +{{^isEnum}}{{>pojo}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache new file mode 100644 index 00000000000..8d80210b4b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache new file mode 100644 index 00000000000..f1d68d014e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache @@ -0,0 +1,75 @@ +import io.swagger.annotations.*; +import java.util.Objects; +{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} + +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>enumClass}}{{/items}}{{/items.isEnum}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + + {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{baseName}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} + return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache new file mode 100644 index 00000000000..a5a683b9748 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache @@ -0,0 +1,82 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + war + {{artifactId}} + {{artifactVersion}} + + + + src/main/java + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + 3.0.0 + + false + + + + + + + + + + javax + javaee-api + 7.0 + provided + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + 3.0.2 + provided + + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + [2.8.3,3) + + + + + io.swagger + swagger-annotations + [1.5.3,2) + + + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache new file mode 100644 index 00000000000..6bff4a4b82d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{#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/cxf-cdi/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceBodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceBodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache new file mode 100644 index 00000000000..a7a154a9822 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file 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 7d57616610d..78cb04420d3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -12,15 +12,23 @@ import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.*; -@Path("/") +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("{{contextPath}}") +@Api(value = "/", description = "{{description}}") public interface {{classname}} { {{#operations}} {{#operation}} + @{{httpMethod}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); +{{#summary}} + @ApiOperation(value = "{{summary}}") +{{/summary}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache new file mode 100644 index 00000000000..9b55d4c7551 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -0,0 +1,34 @@ +package {{package}}.impl; + +import {{package}}.*; +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +{{#description}} +{{/description}} +public class {{classname}}ServiceImpl implements {{classname}} { +{{#operations}} +{{#operation}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + // TODO: Implement... + + {{#returnType}}return null;{{/returnType}} + } + +{{/operation}} +} +{{/operations}} + 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 new file mode 100644 index 00000000000..7d275deb8c2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -0,0 +1,73 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Before; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.transport.common.gzip.GZIPInInterceptor; +import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private {{classname}} api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + + // Example for using Gzipping + GZIPOutInterceptor gzipOutInterceptor = new GZIPOutInterceptor(); + // use Gzipping for first request sent to server + //gzipOutInterceptor.setForce(true); + config.getOutInterceptors().add(gzipOutInterceptor); + + config.getInInterceptors().add(new GZIPInInterceptor()); + + } + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + {{{dataType}}} {{paramName}} = new {{{dataType}}}(); + {{/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/JavaJaxRS/cxf/context.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache new file mode 100644 index 00000000000..1c7aeb4d64d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache @@ -0,0 +1,71 @@ + + + + + + + + + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + + + + + + + + + + + + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache index 5d6d4805f8a..94212231156 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache @@ -3,7 +3,7 @@ public enum {{datatypeWithEnum}} { {{#allowableValues}} - {{#enumVars}}{{name}}({{datatype}}.valueOf("{{value}}")){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{#enumVars}}{{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} {{/allowableValues}} @@ -20,4 +20,4 @@ public enum {{datatypeWithEnum}} { public static {{datatypeWithEnum}} fromValue(String v) { return valueOf(v); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache new file mode 100644 index 00000000000..ef688c10e91 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache @@ -0,0 +1,7 @@ + + + + + swagger-cxf-server + + diff --git a/modules/swagger-codegen/src/main/resources/lumen/licenseinfo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/lumen/licenseinfo.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache index 2c383a41a28..69b4aa7656f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache @@ -2,13 +2,15 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +import javax.validation.constraints.*; {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -{{#isEnum}}{{>enumClass}}{{/isEnum}} -{{^isEnum}}{{>pojo}}{{/isEnum}} +{{#model}} +{{#isEnum}} +{{>enumClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} {{/model}} {{/models}} 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 c214ae2ae84..3078ef74ece 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -1,3 +1,4 @@ +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -7,10 +8,13 @@ import javax.xml.bind.annotation.XmlEnum; @XmlAccessorType(XmlAccessType.FIELD) {{#hasVars}} @XmlType(name = "{{classname}}", propOrder = - { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} + { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} }){{/hasVars}} {{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} +{{#description}} +@ApiModel(description="{{{description}}}") +{{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} @@ -19,16 +23,29 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} @XmlElement(name="{{baseName}}") + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} - public {{{datatypeWithEnum}}} {{getter}}() { + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ +{{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} +{{/vendorExtensions.extraAnnotation}} +{{#useBeanValidation}}{{>../../java/beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } 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 new file mode 100644 index 00000000000..f600dfee8e4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -0,0 +1,197 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + war + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + gen/java + + + + + + + + + maven-war-plugin + + true + + + + + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + +{{#useBeanValidation}} + + + javax.validation + validation-api + ${beanvalidation-version} + provided + +{{/useBeanValidation}} + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + + org.springframework + spring-context + ${spring-version} + + + org.springframework + spring-web + ${spring-version} + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} + ${java.version} + ${java.version} + 1.5.9 + 9.2.9.v20150224 + 2.22.2 + 4.12 + 1.1.7 + 2.5 + 1.1.0.Final + 4.2.5.RELEASE + 3.1.6 + UTF-8 + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md new file mode 100644 index 00000000000..27925cedf44 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md @@ -0,0 +1,23 @@ + +# JAX-RS CXF 3 server application + +## Supported features +* Bean-Validation-API support +* Spring-configuration of Swagger, WADL and Endpoints +* Swagger-API is accessible (CXF3 Swagger2Feature) +* WADL is accessible (CXF WADL-Generator) +* Unit-tests include Gzip-Interceptors for demonstration + + +## Urls to access the REST API + +* Available services listing +http://localhost:8080/swagger-cxf-server/rest/services/ + +* Swagger API + http://localhost:8080/swagger-cxf-server/rest/services/swagger.json + +* CXF WADL + http://localhost:8080/swagger-cxf-server/rest/services?_wadl + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache new file mode 100644 index 00000000000..9d905ae076b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache @@ -0,0 +1,23 @@ + + + + + contextConfigLocation + WEB-INF/context.xml + + + org.springframework.web.context.ContextLoaderListener + + + CXF Service Servlet + CXFServiceServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServiceServlet + /rest/* + + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache index 0867107d993..c5c3143cb94 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache @@ -1,17 +1,44 @@ + /** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ + public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}} + {{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}} + {{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/gson}} - public enum {{{datatypeWithEnum}}} { - {{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + private {{{datatype}}} value; - private String value; - - {{{datatypeWithEnum}}}(String value) { + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{datatype}}} value) { this.value = value; } @Override @JsonValue public String toString() { - return value; + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache index 7aea7b92f22..76c2cbf5a76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache @@ -1,3 +1,42 @@ -public enum {{classname}} { - {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}} -} \ No newline at end of file +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index 993d47bb562..9a7ff6ea6cf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} - @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} + @FormDataParam("{{paramName}}") InputStream {{paramName}}InputStream, + @FormDataParam("{{paramName}}") FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jacksonJsonProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jacksonJsonProvider.mustache index 5efcb449bb5..e82da4051f7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jacksonJsonProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jacksonJsonProvider.mustache @@ -1,8 +1,10 @@ package {{apiPackage}}; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import io.swagger.util.Json; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @@ -11,9 +13,15 @@ import javax.ws.rs.ext.Provider; @Provider @Produces({MediaType.APPLICATION_JSON}) public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - private static ObjectMapper commonMapper = Json.mapper(); public JacksonJsonProvider() { - super.setMapper(commonMapper); + + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .registerModule(new JodaModule()) + .setDateFormat(new RFC3339DateFormat()); + + setMapper(objectMapper); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache index 15442ad4748..59074d1af13 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache @@ -5,6 +5,7 @@ import {{package}}.{{classname}}Service; import {{package}}.factories.{{classname}}ServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache index 3fe8f19d3de..62d45ea9fef 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream, +{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache index c66f8823c4d..d21444dda26 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 {{serverPort}} 60000 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index b9512d2b83c..d52b90c8bec 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -3,14 +3,17 @@ package {{package}}; import java.util.Objects; {{#imports}}import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} -{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -{{#isEnum}}{{>enumOuterClass}}{{/isEnum}} -{{^isEnum}}{{>pojo}}{{/isEnum}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache index 58bfed16381..6e5c1b74115 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache @@ -1,53 +1,102 @@ -{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} +/** + * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + */{{#description}} +@ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} - -{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} - -{{>enumClass}}{{/items}}{{/items.isEnum}} - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{/items}} + {{/items.isEnum}} + {{#jackson}} + @JsonProperty("{{baseName}}") + {{/jackson}} + {{#gson}} + @SerializedName("{{baseName}}") + {{/gson}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ + {{^isReadOnly}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; return this; } + {{#isListContainer}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isListContainer}} + {{#isMapContainer}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMapContainer}} - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{/isReadOnly}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ + {{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} + {{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } + {{^isReadOnly}} + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; } + {{/isReadOnly}} {{/vars}} @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; - } - {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && - {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} } @Override public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); } @Override @@ -64,7 +113,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 0de50ccd1f9..d764934cf77 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 {{serverPort}} 60000 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache index 0f591e315dc..5a0da702332 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache @@ -20,24 +20,25 @@ public class JacksonConfig implements ContextResolver { public JacksonConfig() throws Exception { - objectMapper = new ObjectMapper(); - objectMapper.registerModule(new JodaModule() { - { - addSerializer(DateTime.class, new StdSerializer(DateTime.class) { - @Override - public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { - jgen.writeString(ISODateTimeFormat.dateTimeNoMillis().print(value)); - } - }); - addSerializer(LocalDate.class, new StdSerializer(LocalDate.class) { - @Override - public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { - jgen.writeString(ISODateTimeFormat.date().print(value)); - } - }); + objectMapper = new ObjectMapper() + .setDateFormat(new RFC3339DateFormat()) + .registerModule(new JodaModule() { + { + addSerializer(DateTime.class, new StdSerializer(DateTime.class) { + @Override + public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { + jgen.writeString(ISODateTimeFormat.dateTimeNoMillis().print(value)); + } + }); + addSerializer(LocalDate.class, new StdSerializer(LocalDate.class) { + @Override + public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { + jgen.writeString(ISODateTimeFormat.date().print(value)); + } + }); - } - }); + } + }); } public ObjectMapper getContext(Class arg0) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaDateTimeProvider.mustache index 8010eb85f93..74c24c87770 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaDateTimeProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaDateTimeProvider.mustache @@ -15,7 +15,6 @@ public class JodaDateTimeProvider implements ParamConverterProvider { public static class JodaDateTimeConverter implements ParamConverter { - @Override public DateTime fromString(String string) { try { DateTime dateTime = DateTime.parse(string); @@ -26,13 +25,11 @@ public class JodaDateTimeProvider implements ParamConverterProvider { } } - @Override public String toString(DateTime t) { return t.toString(); } } - @Override public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { if (DateTime.class.equals(type)) { return (ParamConverter) new JodaDateTimeConverter(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaLocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaLocalDateProvider.mustache index 6227bf6df27..0b28c915dd9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaLocalDateProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/JodaLocalDateProvider.mustache @@ -15,7 +15,6 @@ public class JodaLocalDateProvider implements ParamConverterProvider { public static class JodaLocalDateConverter implements ParamConverter { - @Override public LocalDate fromString(String string) { try { LocalDate localDate = LocalDate.parse(string); @@ -26,13 +25,11 @@ public class JodaLocalDateProvider implements ParamConverterProvider { } } - @Override public String toString(LocalDate t) { return t.toString(); } } - @Override public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { if (LocalDate.class.equals(type)) { return (ParamConverter) new JodaLocalDateConverter(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateProvider.mustache index cf52264a1f4..a57e3e74750 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateProvider.mustache @@ -12,19 +12,16 @@ public class LocalDateProvider implements ParamConverterProvider { public static class LocalDateConverter implements ParamConverter { - @Override public LocalDate fromString(String string) { LocalDate localDate = LocalDate.parse(string); return localDate; } - @Override public String toString(LocalDate t) { return t.toString(); } } - @Override public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { if (LocalDate.class.equals(type)) { return (ParamConverter) new LocalDateConverter(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache index f24dabbe283..a3974c3c533 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache @@ -12,19 +12,16 @@ public class OffsetDateTimeProvider implements ParamConverterProvider { public static class OffsetDateTimeConverter implements ParamConverter { - @Override public OffsetDateTime fromString(String string) { - OffsetDateTime OffsetDateTime = OffsetDateTime.parse(string); - return OffsetDateTime; + OffsetDateTime offsetDateTime = OffsetDateTime.parse(string); + return offsetDateTime; } - @Override public String toString(OffsetDateTime t) { return t.toString(); } } - @Override public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { if (OffsetDateTime.class.equals(type)) { return (ParamConverter) new OffsetDateTimeConverter(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..11dc552692c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache @@ -0,0 +1,19 @@ +package {{invokerPackage}}; + +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/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/generatedAnnotation.mustache index 49110fc1ad9..a47b6faa85b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/generatedAnnotation.mustache @@ -1 +1 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file +{{^hideGenerationTimestamp}}@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}"){{/hideGenerationTimestamp}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache index 85d815a79c6..916d909c546 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache @@ -4,14 +4,17 @@ import java.util.Objects; import java.util.ArrayList; {{#imports}}import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} -{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -{{#isEnum}}{{>enumOuterClass}}{{/isEnum}} -{{^isEnum}}{{>pojo}}{{/isEnum}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache index 3373c53b2ce..6c4c547d5c1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -107,7 +107,11 @@ joda-time 2.7 - + + io.swagger + swagger-jaxrs + ${swagger-core-version} + junit junit @@ -145,11 +149,11 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 3.0.11.Final 1.6.3 4.8.1 2.5 - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache index 759335ba9ce..dc2d2eb1ecf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream inputStream, FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache new file mode 100644 index 00000000000..e686a5a0c33 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache @@ -0,0 +1,5 @@ +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath={{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} +server.port={{serverPort}} +spring.jackson.date-format={{basePackage}}.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/application.properties b/modules/swagger-codegen/src/main/resources/JavaSpring/application.properties index 858a5f007b5..8d3a7a8292b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/application.properties +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/application.properties @@ -1,2 +1,2 @@ -springfox.documentation.swagger.v2.path=/api-docs -#server.port=8090 \ No newline at end of file +springfox.documentation.swagger.v2.path=/api-docs +#server.port=8090 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/bodyParams.mustache index f1137ba7073..6845534e7dd 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{^isContainer}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache index 0867107d993..c5c3143cb94 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache @@ -1,17 +1,44 @@ + /** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ + public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}} + {{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}} + {{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/gson}} - public enum {{{datatypeWithEnum}}} { - {{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + private {{{datatype}}} value; - private String value; - - {{{datatypeWithEnum}}}(String value) { + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{datatype}}} value) { this.value = value; } @Override @JsonValue public String toString() { - return value; + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; } } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache index 7aea7b92f22..76c2cbf5a76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache @@ -1,3 +1,42 @@ -public enum {{classname}} { - {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}} -} \ No newline at end of file +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/formParams.mustache index d84de0c3376..2672a2b130c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{#enumVars}}{{{name}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/headerParams.mustache index 7c9e7356a0b..c1b086ed3a7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{#enumVars}}{{{name}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..afe24ed9aba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache @@ -0,0 +1,20 @@ +package {{basePackage}}; + +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/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/homeController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/homeController.mustache index a3528010fb1..bc33ec134e8 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/homeController.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/homeController.mustache @@ -1,16 +1,16 @@ -package {{configPackage}}; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Home redirection to swagger api documentation - */ -@Controller -public class HomeController { - @RequestMapping(value = "/") - public String index() { - System.out.println("swagger-ui.html"); - return "redirect:swagger-ui.html"; - } -} \ No newline at end of file +package {{configPackage}}; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/swagger2SpringBoot.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/swagger2SpringBoot.mustache index ebd4ae4ac55..6d9f64d1a5a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/swagger2SpringBoot.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/swagger2SpringBoot.mustache @@ -1,36 +1,36 @@ -package {{basePackage}}; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.ExitCodeGenerator; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@SpringBootApplication -@EnableSwagger2 -@ComponentScan(basePackages = "{{basePackage}}") -public class Swagger2SpringBoot implements CommandLineRunner { - - @Override - public void run(String... arg0) throws Exception { - if (arg0.length > 0 && arg0[0].equals("exitcode")) { - throw new ExitException(); - } - } - - public static void main(String[] args) throws Exception { - new SpringApplication(Swagger2SpringBoot.class).run(args); - } - - class ExitException extends RuntimeException implements ExitCodeGenerator { - private static final long serialVersionUID = 1L; - - @Override - public int getExitCode() { - return 10; - } - - } -} \ No newline at end of file +package {{basePackage}}; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "{{basePackage}}") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache new file mode 100644 index 00000000000..3130b070174 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache @@ -0,0 +1,83 @@ +{{^interfaceOnly}} +# {{artifactId}} + +## 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 + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" +``` + +### Others + +At first generate the JAR by executing: + +mvn package + +Then manually install the following JARs: + +* target/{{{artifactId}}}-{{{artifactVersion}}}.jar +* target/lib/*.jar +{{/interfaceOnly}} +{{#interfaceOnly}} +# Swagger generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` +{{/interfaceOnly}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache new file mode 100644 index 00000000000..52fedbea776 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache @@ -0,0 +1,10 @@ +package {{package}}; + +import org.springframework.cloud.netflix.feign.FeignClient; +import {{configPackage}}.ClientConfiguration; + +{{=<% %>=}} +@FeignClient(name="${<%title%>.name:<%title%>}", url="${<%title%>.url:<%basePath%>}", configuration = ClientConfiguration.class) +<%={{ }}=%> +public interface {{classname}}Client extends {{classname}} { +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache new file mode 100644 index 00000000000..a7835fc983d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache @@ -0,0 +1,31 @@ +package {{configPackage}}; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Util; + + +public class ApiKeyRequestInterceptor implements RequestInterceptor { + private final String location; + private final String name; + private String value; + + public ApiKeyRequestInterceptor(String location, String name, String value) { + Util.checkNotNull(location, "location", new Object[0]); + Util.checkNotNull(name, "name", new Object[0]); + Util.checkNotNull(value, "value", new Object[0]); + this.location = location; + this.name = name; + this.value = value; + } + + @Override + public void apply(RequestTemplate requestTemplate) { + if(location.equals("header")) { + requestTemplate.header(name, value); + } else if(location.equals("query")) { + requestTemplate.query(name, value); + } + } + +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache new file mode 100644 index 00000000000..2437b30237e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache @@ -0,0 +1,105 @@ +package {{configPackage}}; + +import feign.Logger; +import feign.auth.BasicAuthRequestInterceptor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; +import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; +import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails; +import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +@Configuration +@EnableConfigurationProperties +public class ClientConfiguration { + +{{#authMethods}} + {{#isBasic}} + @Value("${ {{{title}}}.security.{{{name}}}.username:}") + private String {{{name}}}Username; + + @Value("${ {{{title}}}.security.{{{name}}}.password:}") + private String {{{name}}}Password; + + @Bean + @ConditionalOnProperty(name = "{{{title}}}.security.{{{name}}}.username") + public BasicAuthRequestInterceptor {{{name}}}RequestInterceptor() { + return new BasicAuthRequestInterceptor(this.{{{name}}}Username, this.{{{name}}}Password); + } + + {{/isBasic}} + {{#isApiKey}} + @Value("${ {{{title}}}.security.{{{name}}}.key:}") + private String {{{name}}}Key; + + @Bean + @ConditionalOnProperty(name = "{{{title}}}.security.{{{name}}}.key") + public ApiKeyRequestInterceptor {{{name}}}RequestInterceptor() { + return new ApiKeyRequestInterceptor({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{{keyParamName}}}", this.{{{name}}}Key); + } + + {{/isApiKey}} + {{#isOAuth}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + public OAuth2FeignRequestInterceptor {{{name}}}RequestInterceptor() { + return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), {{{name}}}ResourceDetails()); + } + + {{#isCode}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public AuthorizationCodeResourceDetails {{{name}}}ResourceDetails() { + AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); + details.setAccessTokenUri("{{{tokenUrl}}}"); + details.setUserAuthorizationUri("{{{authorizationUrl}}}"); + return details; + } + + {{/isCode}} + {{#isPassword}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public ResourceOwnerPasswordResourceDetails {{{name}}}ResourceDetails() { + ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails(); + details.setAccessTokenUri("{{{tokenUrl}}}"); + return details; + } + + {{/isPassword}} + {{#isApplication}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public ClientCredentialsResourceDetails {{{name}}}ResourceDetails() { + ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails(); + details.setAccessTokenUri("{{{tokenUrl}}}"); + return details; + } + + {{/isApplication}} + {{#isImplicit}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public ImplicitResourceDetails {{{name}}}ResourceDetails() { + ImplicitResourceDetails details = new ImplicitResourceDetails(); + details.setUserAuthorizationUri("{{{authorizationUrl}}}"); + return details; + } + + {{/isImplicit}} + {{/isOAuth}} +{{/authMethods}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache new file mode 100644 index 00000000000..e7547a3ba19 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestParam("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache new file mode 100644 index 00000000000..84e0b0c2f99 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache @@ -0,0 +1,77 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} + ${java.version} + ${java.version} + 1.5.9 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + + + src/main/java + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR2 + pom + import + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + org.springframework.cloud + spring-cloud-starter-feign + + + org.springframework.cloud + spring-cloud-security + + + org.springframework.security.oauth + spring-security-oauth2 + + {{#java8}} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + {{/java8}} + {{^java8}} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + + {{/java8}} + + org.springframework.boot + spring-boot-starter-test + test + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..2e60a5c4b97 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache @@ -0,0 +1,20 @@ +package {{configPackage}}; + +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/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache index d4b4b62c770..f47156b68bc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache @@ -1,14 +1,21 @@ package {{configPackage}}; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Import; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.List; + {{>generatedAnnotation}} @Configuration @ComponentScan(basePackages = "{{apiPackage}}") @@ -51,4 +58,14 @@ public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { } } + @Override + public void configureMessageConverters(List> converters) { + ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .dateFormat( new RFC3339DateFormat()) + .build(); + converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); + super.configureMessageConverters(converters); + } + } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache index b9512d2b83c..d52b90c8bec 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache @@ -3,14 +3,17 @@ package {{package}}; import java.util.Objects; {{#imports}}import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} -{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -{{#isEnum}}{{>enumOuterClass}}{{/isEnum}} -{{^isEnum}}{{>pojo}}{{/isEnum}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache index 58bfed16381..6e5c1b74115 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache @@ -1,53 +1,102 @@ -{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} +/** + * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + */{{#description}} +@ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} - -{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} - -{{>enumClass}}{{/items}}{{/items.isEnum}} - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{/items}} + {{/items.isEnum}} + {{#jackson}} + @JsonProperty("{{baseName}}") + {{/jackson}} + {{#gson}} + @SerializedName("{{baseName}}") + {{/gson}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ + {{^isReadOnly}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; return this; } + {{#isListContainer}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isListContainer}} + {{#isMapContainer}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMapContainer}} - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{/isReadOnly}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ + {{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} + {{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } + {{^isReadOnly}} + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; } + {{/isReadOnly}} {{/vars}} @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; - } - {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && - {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} } @Override public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); } @Override @@ -64,7 +113,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache index d935fb11fd3..5f3f22fc76b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{{name}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache index 35604bf73df..98e2f1c6713 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache @@ -6,7 +6,9 @@ * {{ appDescription }}{{/appDescription}}{{#version}} * Version: {{version}}{{/version}}{{#appContact}} * Contact: {{appContact}}{{/appContact}} +{{^hideGenerationTimestamp}} * Generated at: {{generatedDate}} +{{/hideGenerationTimestamp}} * Generated by: {{generatorClass}} */{{#licenseInfo}} /** diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index 36a484258ec..d277079892c 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -40,10 +40,18 @@ * The authentication methods to be included for all API calls. * @type {Array.} */ -{{/emitJSDoc}}{{=< >=}} this.authentications = {<#authMethods><#isBasic> - '': {type: 'basic'}<#isApiKey> - '': {type: 'apiKey', 'in': <#isKeyInHeader>'header'<^isKeyInHeader>'query', name: ''}<#isOAuth> - '': {type: 'oauth2'}<#hasMore>, +{{/emitJSDoc}}{{=< >=}} this.authentications = { +<#authMethods> +<#isBasic> + '': {type: 'basic'}<^-last>, + +<#isApiKey> + '': {type: 'apiKey', 'in': <#isKeyInHeader>'header'<^isKeyInHeader>'query', name: ''}<^-last>, + +<#isOAuth> + '': {type: 'oauth2'}<^-last>, + + }; <={{ }}=> {{#emitJSDoc}} /** @@ -133,7 +141,7 @@ {{#emitJSDoc}} /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ {{/emitJSDoc}} exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -185,7 +193,7 @@ {{#emitJSDoc}} /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { @@ -330,8 +338,8 @@ * @param {Array.} accepts An array of acceptable response MIME types. * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the * constructor for a complex type.{{^usePromises}} - * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback} callback The callback function. -{{/usePromises}} * @returns {{#usePromises}}{Promise} A Promise object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}. + * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback} callback The callback function.{{/usePromises}} + * @returns {{#usePromises}}{Promise} A {@link https://www.promisejs.org/|Promise} object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}. */ {{/emitJSDoc}} exports.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, @@ -355,7 +363,10 @@ var contentType = this.jsonPreferredMime(contentTypes); if (contentType) { - request.type(contentType); + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } } else if (!request.header['Content-Type']) { request.type('application/json'); } diff --git a/modules/swagger-codegen/src/main/resources/Javascript/README.mustache b/modules/swagger-codegen/src/main/resources/Javascript/README.mustache index 7136e9f326a..9bbf4b4f43a 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/README.mustache @@ -8,7 +8,9 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: {{appVersion}} - Package version: {{projectVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -58,7 +60,7 @@ Please follow the [installation](#installation) instruction and execute the foll ```javascript var {{{moduleName}}} = require('{{{projectName}}}'); {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}} -var defaultClient = {{{moduleName}}}.ApiClient.default; +var defaultClient = {{{moduleName}}}.ApiClient.instance; {{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index d8422549d25..8d515b16b5a 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -38,18 +38,19 @@ * Callback function to receive the result of the operation. * @callback module:<#invokerPackage>/<#apiPackage>/~Callback * @param {String} error Error message, if any. - * @param <#vendorExtensions.x-jsdoc-type><&vendorExtensions.x-jsdoc-type> data The data returned by the service call.<^vendorExtensions.x-jsdoc-type>data This operation does not return a value. + * @param <#vendorExtensions.x-jsdoc-type>{<&vendorExtensions.x-jsdoc-type>} data The data returned by the service call.<^vendorExtensions.x-jsdoc-type>data This operation does not return a value. * @param {String} response The complete HTTP response. */ /**<#summary> * <#notes> * <#allParams><#required> - * @param <&vendorExtensions.x-jsdoc-type> <#hasOptionalParams> + * @param {<&vendorExtensions.x-jsdoc-type>} <#hasOptionalParams> * @param {Object} opts Optional parameters<#allParams><^required> - * @param <&vendorExtensions.x-jsdoc-type> opts. <#defaultValue> (default to <.>)<^usePromises> - * @param {module:<#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/<&classname>~Callback} callback The callback function, accepting three arguments: error, data, response<#returnType> - * data is of type: <&vendorExtensions.x-jsdoc-type> + * @param {<&vendorExtensions.x-jsdoc-type>} opts. <#defaultValue> (default to <.>)<^usePromises> + * @param {module:<#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/<&classname>~Callback} callback The callback function, accepting three arguments: error, data, response<#returnType> + * data is of type: {@link <&vendorExtensions.x-jsdoc-type>}<#usePromises> + * @return {Promise} a {@link https://www.promisejs.org/|Promise}<#returnType>, with data of type {@link <&vendorExtensions.x-jsdoc-type>} */ this. = function() {<#hasOptionalParams> opts = opts || {}; diff --git a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache index ad6e5977058..f08a5c7f5b5 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache @@ -14,7 +14,7 @@ * @class{{#useInheritance}}{{#parent}} * @extends {{#parentModel}}module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}{{/parentModel}}{{^parentModel}}{{#vendorExtensions.x-isArray}}Array{{/vendorExtensions.x-isArray}}{{#vendorExtensions.x-isMap}}Object{{/vendorExtensions.x-isMap}}{{/parentModel}}{{/parent}}{{#interfaces}} * @implements module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}} - * @param {{name}} {{{vendorExtensions.x-jsdoc-type}}} {{#description}}{{{description}}}{{/description}}{{/vendorExtensions.x-all-required}} + * @param {{name}} {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{#description}}{{{description}}}{{/description}}{{/vendorExtensions.x-all-required}} */ {{/emitJSDoc}} var exports = function({{#vendorExtensions.x-all-required}}{{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) { @@ -56,7 +56,7 @@ {{#emitJSDoc}} /**{{#description}} * {{{description}}}{{/description}} - * @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} * @default {{{defaultValue}}}{{/defaultValue}} */ {{/emitJSDoc}} @@ -66,7 +66,7 @@ {{#emitJSDoc}} /**{{#description}} * {{{description}}}{{/description}} - * @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} * @default {{{defaultValue}}}{{/defaultValue}} */ {{/emitJSDoc}} @@ -78,7 +78,7 @@ exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaul * Returns {{{description}}}{{/description}}{{#minimum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} - * @return {{{vendorExtensions.x-jsdoc-type}}} + * @return {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> */ {{/emitJSDoc}} exports.prototype.{{getter}} = function() { @@ -88,7 +88,7 @@ exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaul {{#emitJSDoc}} /**{{#description}} * Sets {{{description}}}{{/description}} - * @param {{{vendorExtensions.x-jsdoc-type}}} {{name}}{{#description}} {{{description}}}{{/description}} + * @param {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{name}}{{#description}} {{{description}}}{{/description}} */ {{/emitJSDoc}} exports.prototype.{{setter}} = function({{name}}) { 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 20a8ce8e9fb..3c40b1d84e9 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 @@ -1,6 +1,7 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AspNet5ServerCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen +io.swagger.codegen.languages.ConfluenceWikiGenerator io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.CppRestClientCodegen io.swagger.codegen.languages.DartClientCodegen @@ -13,6 +14,7 @@ io.swagger.codegen.languages.JavaJerseyServerCodegen io.swagger.codegen.languages.JavaCXFServerCodegen io.swagger.codegen.languages.JavaResteasyServerCodegen io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen +io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen @@ -35,6 +37,7 @@ io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SpringCodegen io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticHtmlGenerator +io.swagger.codegen.languages.StaticHtml2Generator io.swagger.codegen.languages.SwaggerGenerator io.swagger.codegen.languages.SwaggerYamlGenerator io.swagger.codegen.languages.SwiftCodegen @@ -49,3 +52,5 @@ io.swagger.codegen.languages.ClojureClientCodegen io.swagger.codegen.languages.HaskellServantCodegen io.swagger.codegen.languages.LumenServerCodegen io.swagger.codegen.languages.GoServerCodegen +io.swagger.codegen.languages.ErlangServerCodegen +io.swagger.codegen.languages.UndertowCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md index db2dfccec36..664e1755933 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md @@ -26,7 +26,7 @@ CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user #### NPM #### You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. +You can also 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. 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 df1b5e05ace..5bf0ed7fb92 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -10,7 +10,7 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "{{basePath}}"; +const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ''); export interface FetchArgs { url: string; @@ -41,14 +41,14 @@ export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ * {{{description}}} */ {{/description}} - "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } {{#hasEnums}} {{#vars}} {{#isEnum}} -export type {{classname}}{{datatypeWithEnum}} = {{#allowableValues}}{{#values}}"{{.}}"{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; +export type {{{enumName}}} = {{#allowableValues}}{{#values}}"{{{.}}}"{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; {{/isEnum}} {{/vars}} {{/hasEnums}} @@ -161,7 +161,26 @@ export class {{classname}} extends BaseAPI { return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(this.fetch, this.basePath); } {{/operation}} -} +}; + +/** + * {{classname}} - factory interface{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}Factory = function (fetch?: FetchAPI, basePath?: string) { + return { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(fetch, basePath); + }, +{{/operation}} + } +}; {{/operations}} {{/apis}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache index 0c08f91af78..7743c15718d 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache @@ -11,24 +11,33 @@ import org.joda.time.DateTime {{#models}} {{#model}} - case class {{classname}} ( - {{#vars}}{{#description}}/* {{{description}}} */ - {{/description}}{{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} - {{/vars}} extends ApiModel + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}} + {{/vars}} +) extends ApiModel {{#hasEnums}} object {{classname}}Enums { - {{#vars}}{{#isEnum}}type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value - {{/isEnum}}{{/vars}} - {{#vars}}{{#isEnum}}object {{datatypeWithEnum}} extends Enumeration { + {{#vars}} + {{#isEnum}} + type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}} + {{/vars}} + {{#vars}} + {{#isEnum}} + object {{datatypeWithEnum}} extends Enumeration { {{#_enum}} val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") {{/_enum}} } - {{/isEnum}}{{/vars}} + {{/isEnum}} + {{/vars}} } {{/hasEnums}} {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index b7bd04afffb..ea666198674 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.8 + 1.5.9 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/android/Pair.mustache b/modules/swagger-codegen/src/main/resources/android/Pair.mustache index 5456028a1a0..60e15c94ed4 100644 --- a/modules/swagger-codegen/src/main/resources/android/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/android/Pair.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class Pair { diff --git a/modules/swagger-codegen/src/main/resources/android/README.mustache b/modules/swagger-codegen/src/main/resources/android/README.mustache index 8091b0adb06..4834927cd51 100644 --- a/modules/swagger-codegen/src/main/resources/android/README.mustache +++ b/modules/swagger-codegen/src/main/resources/android/README.mustache @@ -117,7 +117,7 @@ Class | Method | HTTP request | Description ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/android/api.mustache b/modules/swagger-codegen/src/main/resources/android/api.mustache index 5f786e503a0..5ddd06f90da 100644 --- a/modules/swagger-codegen/src/main/resources/android/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; import {{invokerPackage}}.ApiException; diff --git a/modules/swagger-codegen/src/main/resources/android/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/apiException.mustache index be5255e2568..8d9da2fbe5d 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiException.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class ApiException extends Exception { diff --git a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache index a2df0ea9b7c..0dac1bb8f59 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import org.apache.http.*; @@ -15,6 +16,8 @@ import org.apache.http.params.*; import org.apache.http.util.EntityUtils; import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.net.URLEncoder; @@ -24,8 +27,6 @@ import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; @@ -206,7 +207,11 @@ public class ApiInvoker { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { diff --git a/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache b/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache index 08ce4409f7a..671f71a4fc2 100644 --- a/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache +++ b/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import org.apache.http.client.methods.*; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache index 5456028a1a0..60e15c94ed4 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class Pair { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index 5d9ecb32066..0d18ad5572e 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; import {{invokerPackage}}.ApiInvoker; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache index be5255e2568..8d9da2fbe5d 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class ApiException extends Exception { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index e76bf1357e1..d57d8bb058f 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache @@ -1,6 +1,8 @@ +{{>licenseInfo}} package {{invokerPackage}}; import com.android.volley.Cache; +import com.android.volley.DefaultRetryPolicy; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; @@ -18,6 +20,7 @@ import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -221,6 +224,7 @@ public class ApiInvoker { } public static ApiInvoker getInstance() { + if (INSTANCE == null) initializeInstance(); return INSTANCE; } @@ -229,7 +233,11 @@ public class ApiInvoker { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { @@ -485,7 +493,12 @@ public class ApiInvoker { } else { request = new PatchRequest(url, headers, null, null, stringRequest, errorListener); } - } + } + + if (request != null) { + request.setRetryPolicy(new DefaultRetryPolicy((int)TimeUnit.SECONDS.toMillis(this.connectionTimeout), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); + } + return request; } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache index 44c5ed96eca..2208935ee42 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; @@ -52,9 +53,9 @@ public class ApiKeyAuth implements Authentication { } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache index 265c74cb76f..1a185437a90 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache index 64fc61f95c1..51017997ed4 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache index 7eb4fe4aaba..72b5e0baab8 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache index 74f1aafd64d..e8abab33c52 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache @@ -62,7 +62,7 @@ ext { httpmime_version = "4.5.2" httpcore_version = "4.4.4" httpclient_version = "4.3.3" - volley_version = "1.0.19" + volley_version = "1.0.0" junit_version = "4.12" robolectric_version = "3.0" concurrent_unit_version = "0.4.2" @@ -74,7 +74,7 @@ dependencies { compile "org.apache.httpcomponents:httpcore:$httpcore_version" compile "org.apache.httpcomponents:httpmime:$httpmime_version" compile "org.apache.httpcomponents:httpclient-android:$httpclient_version" - compile "com.mcxiaoke.volley:library:${volley_version}@aar" + compile "com.android.volley:volley:${volley_version}" testCompile "junit:junit:$junit_version" testCompile "org.robolectric:robolectric:${robolectric_version}" testCompile "net.jodah:concurrentunit:${concurrent_unit_version}" diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache index ae8d18d3731..0460feef71b 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache @@ -1,10 +1,16 @@ +{{>licenseInfo}} package {{invokerPackage}}; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; +import java.util.Date; import {{modelPackage}}.*; public class JsonUtil { @@ -14,6 +20,11 @@ public class JsonUtil { gsonBuilder = new GsonBuilder(); gsonBuilder.serializeNulls(); gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); } public static Gson getGson() { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache index df99de87403..e64bb09c8ab 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache @@ -1,18 +1,23 @@ +{{>licenseInfo}} package {{package}}; {{#imports}}import {{import}}; {{/imports}} - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} {{#models}} -{{#model}}{{#description}} +{{#model}} +{{#description}} /** * {{description}} - **/{{/description}} + **/ +{{/description}} @ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { +public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#serializableModel}}implements Serializable {{/serializableModel}}{ {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} @@ -47,7 +52,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}({{name}} == null ? {{classVarName}}.{{name}} == null : {{name}}.equals({{classVarName}}.{{name}})){{#hasMore}} && + return {{#vars}}(this.{{name}} == null ? {{classVarName}}.{{name}} == null : this.{{name}}.equals({{classVarName}}.{{name}})){{#hasMore}} && {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} } @@ -56,7 +61,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public int hashCode() { int result = 17; {{#vars}} - result = 31 * result + ({{name}} == null ? 0: {{name}}.hashCode());{{#hasMore}}{{/hasMore}} + result = 31 * result + (this.{{name}} == null ? 0: this.{{name}}.hashCode()); {{/vars}} return result; } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache index b5def5f589f..7dcc613d0f0 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache index ec225b5a46c..2bccdf40a61 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache index 3607a03eeab..5415ab602a2 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache index 7d0d1fe1c14..183fe15b9b5 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache index a9dd14b0a7b..88cf2edce8e 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/android/model.mustache b/modules/swagger-codegen/src/main/resources/android/model.mustache index df99de87403..1b4d62b4468 100644 --- a/modules/swagger-codegen/src/main/resources/android/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/model.mustache @@ -47,7 +47,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}({{name}} == null ? {{classVarName}}.{{name}} == null : {{name}}.equals({{classVarName}}.{{name}})){{#hasMore}} && + return {{#vars}}(this.{{name}} == null ? {{classVarName}}.{{name}} == null : this.{{name}}.equals({{classVarName}}.{{name}})){{#hasMore}} && {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} } @@ -56,7 +56,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public int hashCode() { int result = 17; {{#vars}} - result = 31 * result + ({{name}} == null ? 0: {{name}}.hashCode());{{#hasMore}}{{/hasMore}} + result = 31 * result + (this.{{name}} == null ? 0: this.{{name}}.hashCode()); {{/vars}} return result; } diff --git a/modules/swagger-codegen/src/main/resources/android/pom.mustache b/modules/swagger-codegen/src/main/resources/android/pom.mustache index bf11a6625c5..e073253123d 100644 --- a/modules/swagger-codegen/src/main/resources/android/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/pom.mustache @@ -145,7 +145,7 @@ - 1.5.8 + 1.5.9 2.3.1 4.8.1 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache index 8ff1b8faeed..0765ead2db2 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache @@ -1,10 +1,12 @@ -FROM microsoft/aspnet:1.0.0-rc1-final +FROM microsoft/dotnet:latest + +ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 RUN mkdir -p /app/{{packageName}} COPY . /app/{{packageName}} WORKDIR /app/{{packageName}} -RUN ["dnu", "restore"] -RUN ["dnu", "pack", "--out", "artifacts"] EXPOSE 5000/tcp -ENTRYPOINT ["dnx", "-p", "project.json", "web"] + +RUN ["dotnet", "restore"] +ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config b/modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config new file mode 100644 index 00000000000..01f3d1f203f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache new file mode 100644 index 00000000000..ab465c42516 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Builder; + +namespace {{packageName}} +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel(options => + { + // options.ThreadCount = 4; + // options.UseHttps("cert.pfx", "certpassword"); + options.NoDelay = true; + options.UseConnectionLogging(); + }) + .UseUrls("http://+:5000" /*, "https://+:5001" */) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache new file mode 100644 index 00000000000..16f3716730d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + {{packageGuid}} + {{packageName}} + .\obj + .\bin\ + v4.6 + + + 2.0 + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json b/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json index 7d41a0f84b9..45a5f3319a5 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json @@ -1,12 +1,28 @@ { + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:50352/", + "sslPort": 0 + } + }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "swagger/ui", + "launchUrl": "swagger/ui/index.html", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "web": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "http://localhost:5000/swagger/ui/index.html", "environmentVariables": { - "ASPNET_ENV": "Development" + "ASPNETCORE_ENVIRONMENT": "Development" } } } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/README.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/README.mustache new file mode 100644 index 00000000000..451508ad676 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/README.mustache @@ -0,0 +1,27 @@ +# {{packageName}} - ASP.NET Core 1.0 Server + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Run + +Linux/OS X: + +``` +sh build.sh +``` + +Windows: + +``` +build.bat +``` + +## Run in Docker + +``` +cd src/{{packageName}} +docker build -t {{packageName}} . +docker run -p 5000:5000 {{packageName}} +``` diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache new file mode 100644 index 00000000000..c86909a4c8b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache @@ -0,0 +1,26 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFF6BF88-8A7D-4736-AF81-31BCE86B19BD}" + ProjectSection(SolutionItems) = preProject + global.json = global.json + EndProjectSection +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.xproj", "{{packageGuid}}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {{packageGuid}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU + {{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU + {{packageGuid}}.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/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache index c4e9d328cc7..80709bd068f 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache @@ -1,136 +1,81 @@ +{{>partial_header}} using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Hosting; +using System.Threading.Tasks; +using System.Xml.XPath; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.PlatformAbstractions; using Newtonsoft.Json.Serialization; -using Swashbuckle.SwaggerGen; -using Swashbuckle.SwaggerGen.XmlComments; +using Swashbuckle.Swagger.Model; +using Swashbuckle.SwaggerGen.Annotations; namespace {{packageName}} { public class Startup { private readonly IHostingEnvironment _hostingEnv; - private readonly IApplicationEnvironment _appEnv; - public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) + public IConfigurationRoot Configuration { get; } + + public Startup(IHostingEnvironment env) { _hostingEnv = env; - _appEnv = appEnv; - // Set up configuration sources. var builder = new ConfigurationBuilder() - .AddJsonFile("appsettings.json") + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } - - public IConfigurationRoot Configuration { get; set; } - + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - string xmlComments = string.Format(@"{0}{4}artifacts{4}{1}{4}{2}{3}{4}{{packageName}}.xml", - GetSolutionBasePath(), - _appEnv.Configuration, - _appEnv.RuntimeFramework.Identifier.ToLower(), - _appEnv.RuntimeFramework.Version.ToString().Replace(".", string.Empty), - Path.DirectorySeparatorChar); - // Add framework services. services.AddMvc() .AddJsonOptions( opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); - - // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. - // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. - // services.AddWebApiConventions(); - + services.AddSwaggerGen(); - services.ConfigureSwaggerDocument(options => + + services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "{{packageName}}", - Description = "{{packageName}} (ASP.NET 5 Web API 2.x)" + Description = "{{packageName}} (ASP.NET Core 1.0)" }); - - options.OperationFilter(new ApplyXmlActionCommentsFixed(xmlComments)); - }); - services.ConfigureSwaggerSchema(options => { - options.DescribeAllEnumsAsStrings = true; - options.ModelFilter(new ApplyXmlTypeCommentsFixed(xmlComments)); + options.DescribeAllEnumsAsStrings(); + + var comments = new XPathDocument($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml"); + options.OperationFilter(comments); + options.ModelFilter(comments); }); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); - app.UseIISPlatformHandler(); - + app.UseMvc(); + app.UseDefaultFiles(); app.UseStaticFiles(); - app.UseMvc(); - - app.UseSwaggerGen(); + app.UseSwagger(); app.UseSwaggerUi(); } - - // Taken from https://github.com/domaindrivendev/Ahoy/blob/master/test/WebSites/Basic/Startup.cs - private string GetSolutionBasePath() - { - var dir = Directory.CreateDirectory(_appEnv.ApplicationBasePath); - while (dir.Parent != null) - { - if (dir.GetDirectories("artifacts").Any()) - return dir.FullName; - - dir = dir.Parent; - } - throw new InvalidOperationException("Failed to detect solution base path - artifacts not found. Did you run dnu pack --out artifacts?"); - } - - // Entry point for the application. - public static void Main(string[] args) => WebApplication.Run(args); - } - - - // using Swashbuckle.SwaggerGen.XmlComments; - public class ApplyXmlTypeCommentsFixed : ApplyXmlTypeComments - { - public ApplyXmlTypeCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlTypeCommentsFixed(string filePath): base(filePath) - { - - } - } - - public class ApplyXmlActionCommentsFixed : ApplyXmlActionComments - { - public ApplyXmlActionCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlActionCommentsFixed(string filePath): base(filePath) - { - - } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json b/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json index e5472e562b7..c6af7d9b069 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json +++ b/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json @@ -2,7 +2,7 @@ "Logging": { "IncludeScopes": false, "LogLevel": { - "Default": "Verbose", + "Default": "Information", "System": "Information", "Microsoft": "Information" } diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache new file mode 100644 index 00000000000..b39b7232a1c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache @@ -0,0 +1,20 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + +@echo off + +dotnet restore src\{{packageName}} +dotnet build src\{{packageName}} +echo Now, run the following to start the project: dotnet run -p src\{{packageName}}\project.json web. +echo. diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/build.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/build.mustache deleted file mode 100644 index 0a63bfeaf3d..00000000000 --- a/modules/swagger-codegen/src/main/resources/aspnet5/build.mustache +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash - -if ! type dnvm > /dev/null 2>&1; then - source /usr/local/lib/dnx/bin/dnvm.sh -fi - -if ! type dnu > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then - dnvm install latest -runtime coreclr -alias default - dnvm install default -runtime mono -alias default -else - dnvm use default -runtime mono -fi - -dnu restore src/{{packageName}}/ && \ - dnu build src/{{packageName}}/ && \ - dnu pack src/{{packageName}}/ --out artifacts && \ - echo "Now, run the following to start the project: dnx --project src/{{packageName}}/project.json web" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache new file mode 100644 index 00000000000..179fe5fb61f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +dotnet restore src/{{packageName}}/ && \ + dotnet build src/{{packageName}}/ && \ + echo "Now, run the following to start the project: dotnet run -p src/{{packageName}}/project.json web" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache index 592ef42362b..72c5480ad0d 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +7,7 @@ using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using {{packageName}}.Models; @@ -15,9 +16,8 @@ namespace {{packageName}}.Controllers { {{#operations}} /// /// {{description}} - /// {{#description}}{{#basePath}} - [Route("{{{basePath}}}")] - {{/basePath}}[Description("{{description}}")]{{/description}} + /// {{#description}} + [Description("{{description}}")]{{/description}} public class {{classname}}Controller : Controller { {{#operation}} @@ -28,7 +28,7 @@ namespace {{packageName}}.Controllers /// {{description}}{{/allParams}}{{#responses}} /// {{message}}{{/responses}} [{{httpMethod}}] - [Route("{{path}}")] + [Route("{{basePathWithoutHost}}{{path}}")] [SwaggerOperation("{{operationId}}")]{{#returnType}} [SwaggerResponse(200, type: typeof({{&returnType}}))]{{/returnType}} public virtual {{#returnType}}IActionResult{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/global.json b/modules/swagger-codegen/src/main/resources/aspnet5/global.json index 4a6d1feac95..e5360d025ec 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/global.json +++ b/modules/swagger-codegen/src/main/resources/aspnet5/global.json @@ -1,8 +1,7 @@ { - "projects": [ "src", "." ], + "projects": [ "src", "test" ], "sdk": { - "version": "1.0.0-rc1-final", - "runtime": "coreclr", - "architecture": "x64" + "version": "1.0.0-preview2-003121", + "runtime": "coreclr" } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache index 08aaed01f3d..58325e8fe24 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Linq; using System.IO; @@ -15,6 +16,7 @@ namespace {{packageName}}.Models /// /// {{description}} /// + [DataContract] public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}> { /// @@ -51,6 +53,7 @@ namespace {{packageName}}.Models /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} /// {{#description}} /// {{{description}}}{{/description}} + [DataMember(Name="{{baseName}}")] public {{{datatype}}} {{name}} { get; set; } {{/vars}} @@ -63,7 +66,8 @@ namespace {{packageName}}.Models { var sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); - {{#vars}}sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); {{/vars}} sb.Append("}\n"); return sb.ToString(); diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache new file mode 100644 index 00000000000..f7477da5c47 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache @@ -0,0 +1,25 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache new file mode 100644 index 00000000000..432ba86d5a9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache @@ -0,0 +1,88 @@ +{ + "title": "Swagger UI", + "version": "{{packageVersion}}-*", + "copyright": "{{packageName}}", + "description": "{{packageName}}", + "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0", + "type": "platform" + }, + "Microsoft.AspNetCore.Mvc": "1.0.0", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0", + "Microsoft.AspNetCore.StaticFiles": "1.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", + "Microsoft.Extensions.Configuration.Json": "1.0.0", + "Microsoft.Extensions.Logging": "1.0.0", + "Microsoft.Extensions.Logging.Console": "1.0.0", + "Microsoft.Extensions.Logging.Debug": "1.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", + "Microsoft.EntityFrameworkCore": "1.0.0", + "Swashbuckle.SwaggerGen": "6.0.0-beta901", + "Swashbuckle.SwaggerUi": "6.0.0-beta901" + }, + + "tools": { + "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final", + + "Microsoft.Extensions.SecretManager.Tools": { + "imports": [ + "netstandard1.6", + "portable-net45+win8+dnxcore50", + "portable-net45+win8" + ], + "version": "1.0.0-preview2-final" + } + }, + + "frameworks": { + "netcoreapp1.0": { + "imports": [ + "dotnet5.6", + "dnxcore50", + "netstandard1.6", + "portable-net452+win81" + ] + } + }, + + "buildOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true, + "xmlDoc": true, + "compile": { + "exclude": [ + "wwwroot", + "node_modules", + "bower_components" + ] + } + }, + + "runtimeOptions": { + "configProperties": { + "System.GC.Server": true + } + }, + + "publishOptions": { + "include": [ + "wwwroot", + "Views", + "Areas/**/Views", + "appsettings.json", + "web.config" + ], + "exclude": [ + "**.user", + "**.vspscc" + ] + }, + + "scripts": { + "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] + } +} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/project.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/project.mustache deleted file mode 100644 index 018084bc7e1..00000000000 --- a/modules/swagger-codegen/src/main/resources/aspnet5/project.mustache +++ /dev/null @@ -1,41 +0,0 @@ -{ - "version": "{{packageVersion}}-*", - "compilationOptions": { - "emitEntryPoint": true - }, - "tooling": { - "defaultNamespace": "{{packageName}}" - }, - - "dependencies": { - "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", - "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", - "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", - "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", - "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final", - "Microsoft.Extensions.Logging": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Debug" : "1.0.0-rc1-final", - "Swashbuckle.SwaggerGen": "6.0.0-rc1-final", - "Swashbuckle.SwaggerUi": "6.0.0-rc1-final" - }, - - "commands": { - "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://0.0.0.0:5000" - }, - - "frameworks": { - "dnx451": { }, - "dnxcore50": { } - }, - - "exclude": [ - "wwwroot", - "node_modules", - "bower_components" - ], - "publishExclude": [ - "**.user", - "**.vspscc" - ] -} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/web.config b/modules/swagger-codegen/src/main/resources/aspnet5/web.config new file mode 100644 index 00000000000..a3b9f6add9c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/web.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache index 7f2edfd9aea..4595c877299 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -25,23 +25,34 @@ class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiC {{#required}} {{^isPrimitiveType}} if ({{paramName}} == null) throw new Exception("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") - {{/isPrimitiveType}} + {{#isString}} + if ({{paramName}} == null) throw new Exception("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") + + {{/isString}} {{/required}} {{/allParams}} {{#queryParams}} {{^required}} - if ({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString } - + {{paramName}} match { + case Some(param) => queryParams += "{{baseName}}" -> param.toString + case _ => queryParams + } {{/required}} {{#required}} - if ({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString - + queryParams += "{{baseName}}" -> {{paramName}}.toString {{/required}} {{/queryParams}} - {{#headerParams}} + {{^required}} + {{paramName}} match { + case Some(param) => headerParams += "{{baseName}}" -> param.toString + case _ => headerParams + } + {{/required}} + {{#required}} headerParams += "{{baseName}}" -> {{paramName}}.toString + {{/required}} {{/headerParams}} val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{paramName}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}}) diff --git a/modules/swagger-codegen/src/main/resources/codegen/README.mustache b/modules/swagger-codegen/src/main/resources/codegen/README.mustache index 268a84a0edd..9fed9dbb92c 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/README.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/README.mustache @@ -1,7 +1,7 @@ # Swagger Codegen for the {{name}} library ## Overview -This is a boiler-plate project to generate your own client library with Swagger. It's goal is +This is a boiler-plate project to generate your own client library with Swagger. Its goal is to get you started with the basic plumbing so you can put in your own logic. It won't work without your changes applied. @@ -46,7 +46,7 @@ mvn package In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: ``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l {{name}} -o ./test +java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test ``` Now your templates are available to the client generator and you can write output values @@ -67,7 +67,7 @@ the object you have available during client generation: # -DdebugOperations prints operations passed to the template engine # -DdebugSupportingFiles prints additional data passed to the template engine -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l {{name}} -o ./test +java -DdebugOperations -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test ``` Will, for example, output the debug info for operations. You can use this info diff --git a/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache new file mode 100644 index 00000000000..28312bb4b74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache @@ -0,0 +1,94 @@ +h1. {{{appName}}} {{{appDescription}}} + +{{#version}}*Version:* {{{version}}}{{/version}} + +---- + +{toc:printable=true|style=square|minLevel=2|maxLevel=3|type=list|outline=false|include=.*} + +h2. Endpoints +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + h3. {{nickname}} + {status:colour=Yellow|title={{httpMethod}}|subtle=false} + {code} + {{httpMethod}} {{path}} + {code} + *Summary:* {{summary}} + *Description:* {{notes}} + + + h4. Parameters + {{#hasPathParams}} + h5. Path Parameters + ||Name||Description||Required||Default||Pattern|| + {{#pathParams}}{{>param}} + {{/pathParams}} + {{/hasPathParams}} + + {{#hasBodyParam}} + h5. Body Parameter + ||Name||Description||Required||Default||Pattern|| + {{#bodyParams}}{{>param}} + {{/bodyParams}} + {{/hasBodyParam}} + + {{#hasHeaderParams}} + h5. Header Parameters + ||Name||Description||Required||Default||Pattern|| + {{#headerParam}}{{>param}} + {{/headerParam}} + {{/hasHeaderParams}} + + {{#hasQueryParams}} + h5. Query Parameters + ||Name||Description||Required||Default||Pattern|| + {{#queryParams}}{{>param}} + {{/queryParams}} + {{/hasQueryParams}} + + + + + h4. Responses + {{#responses}} + *Status Code:* {{code}} + *Message:* {{message}} + {code:title=Response Type} +{{{dataType}}} + {code} + See [#models] + + {{#hasExamples}} + {{#examples}} + {code:title=Example {{{contentType}}} |collapse=true } + {{{example}}} +{code} + {{/examples}} + {{/hasExamples}} + + + {code:title=Response Schema |collapse=true} +{{{jsonSchema}}} + {code} + {{#examples}} + {code:title=Example {{{contentType}}} |collapse=true } +{{{example}}} + {code} + {{/examples}} + {{/responses}} + ---- +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +h2. Models + +{{#models}} + {{#model}} + h3. {{classname}} + ||Field Name||Required||Type||Description|| + {{#vars}} |{{name}} |{{#isNotRequired}}(x){{/isNotRequired}} |{{datatype}} |{{description}} | + {{/vars}} + {{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache new file mode 100644 index 00000000000..fd7d3166c37 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache @@ -0,0 +1 @@ +|{{paramName}} |{{description}} |{{^required}}(x){{/required}}{{#required}}(/){{/required}} |{{defaultValue}} | {{pattern}} | \ No newline at end of file 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 b6312e37a7f..21c5eff5553 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -62,10 +62,19 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r { responseHttpContentType = U("multipart/form-data"); } + {{#vendorExtensions.x-codegen-response-ishttpcontent}} + else + { + //It's going to be binary, so just use the first one. + responseHttpContentType = *responseHttpContentTypes.begin(); + } + {{/vendorExtensions.x-codegen-response-ishttpcontent}} + {{^vendorExtensions.x-codegen-response-ishttpcontent}} else { throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type")); } + {{/vendorExtensions.x-codegen-response-ishttpcontent}} headerParams[U("Accept")] = responseHttpContentType; @@ -189,17 +198,17 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { - // 1xx - informational : OK - // 2xx - successful : OK - // 3xx - redirection : OK - // 4xx - client error : not OK - // 5xx - client error : not OK - if (response.status_code() >= 400) - { - throw ApiException(response.status_code() - , U("error calling {{operationId}}: ") + response.reason_phrase() - , std::make_shared(response.extract_utf8string(true).get())); - } + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (response.status_code() >= 400) + { + throw ApiException(response.status_code() + , U("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"))) @@ -213,6 +222,17 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r } } + {{#vendorExtensions.x-codegen-response-ishttpcontent}} + return response.extract_vector(); + }) + .then([=](std::vector response) + { + HttpContent result; + std::shared_ptr stream = std::make_shared(std::string(response.begin(), response.end())); + result.setData(stream); + return result; + {{/vendorExtensions.x-codegen-response-ishttpcontent}} + {{^vendorExtensions.x-codegen-response-ishttpcontent}} return response.extract_string(); }) .then([=](utility::string_t response) @@ -253,12 +273,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r // } else { - throw ApiException(500 - , U("error calling findPetsByStatus: unsupported response type")); + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); } return result; {{/returnType}} + {{/vendorExtensions.x-codegen-response-ishttpcontent}} }); } {{/operation}} 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 54112543316..a13771f4311 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -33,11 +33,11 @@ utility::string_t ApiClient::parameterToString(utility::string_t value) } utility::string_t ApiClient::parameterToString(int64_t value) { - return std::to_wstring(value); + return utility::conversions::to_string_t(std::to_string(value)); } utility::string_t ApiClient::parameterToString(int32_t value) { - return std::to_wstring(value); + return utility::conversions::to_string_t(std::to_string(value)); } pplx::task ApiClient::callApi( 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 e79f575061f..27f53b8e0c1 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache @@ -40,9 +40,9 @@ public: virtual void setData( std::shared_ptr value ); virtual void writeTo( std::ostream& stream ); - + protected: - // NOTE: no utility::string_t here because those strings can only contain ascii + // NOTE: no utility::string_t here because those strings can only contain ascii utility::string_t m_ContentDisposition; utility::string_t m_Name; utility::string_t m_FileName; 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 a1985735d4a..26970c20d8d 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache @@ -29,12 +29,12 @@ web::json::value {{classname}}::toJson() const { web::json::value val = web::json::value::object(); - {{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) { val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); } {{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ std::vector jsonArray; for( auto& item : m_{{name}} ) { @@ -48,24 +48,24 @@ web::json::value {{classname}}::toJson() const } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) { val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); } {{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); - {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} return val; } void {{classname}}::fromJson(web::json::value& val) { - {{#vars}}{{#isPrimitiveType}}{{^required}}if(val.has_field(U("{{baseName}}"))) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}"))) { {{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); } {{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ m_{{name}}.clear(); std::vector jsonArray; {{^required}}if(val.has_field(U("{{baseName}}"))) @@ -73,8 +73,8 @@ void {{classname}}::fromJson(web::json::value& val) {{/required}} for( auto& item : val[U("{{baseName}}")].as_array() ) { - {{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item)); - {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); + {{#isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{items.baseType}}FromJson(item)); + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); {{/items.isDateTime}}{{^items.isDateTime}} if(item.is_null()) @@ -87,13 +87,13 @@ void {{classname}}::fromJson(web::json::value& val) newItem->fromJson(item); m_{{name}}.push_back( newItem ); } - {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + {{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}} } {{^required}} } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}"))) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(val.has_field(U("{{baseName}}"))) { {{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); @@ -111,23 +111,23 @@ void {{classname}}::fromJson(web::json::value& val) {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}}); new{{name}}->fromJson(val[U("{{baseName}}")]); {{setter}}( newItem ); - {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } 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('.')) - { - namePrefix += U("."); - } + if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + { + namePrefix += U("."); + } - {{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); } {{/required}}{{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ std::vector jsonArray; for( auto& item : m_{{name}} ) { @@ -141,7 +141,7 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^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}})); @@ -155,23 +155,23 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); {{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); - {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } 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('.')) - { - namePrefix += U("."); - } + if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + { + namePrefix += U("."); + } - {{#vars}}{{#isPrimitiveType}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) { {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); } {{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ m_{{name}}.clear(); {{^required}}if(multipart->hasContent(U("{{baseName}}"))) { @@ -180,8 +180,8 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); for( auto& item : jsonArray.as_array() ) { - {{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item)); - {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); + {{#isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{items.baseType}}FromJson(item)); + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); {{/items.isDateTime}}{{^items.isDateTime}} if(item.is_null()) @@ -194,13 +194,13 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, newItem->fromJson(item); m_{{name}}.push_back( newItem ); } - {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + {{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}} } {{^required}} } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) { {{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); @@ -218,21 +218,21 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}}); new{{name}}->fromMultiPart(multipart, U("{{baseName}}.")); {{setter}}( new{{name}} ); - {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } {{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}() { - return m_{{name}}; + return m_{{name}}; } {{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{classname}}::{{getter}}() const { - return m_{{name}}; + return m_{{name}}; } void {{classname}}::{{setter}}({{{datatype}}} value) { - m_{{name}} = value; + m_{{name}} = value; {{^required}}m_{{name}}IsSet = true;{{/required}} } {{/isNotContainer}} 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 4d9ee6b40a0..787e390d0fd 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache @@ -306,7 +306,7 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr std::string str((std::istreambuf_iterator(*data.get())), std::istreambuf_iterator()); - return utility::conversions::to_utf16string(str); + return utility::conversions::to_string_t(str); } utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr val) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 5ce03342baa..108b85e48f8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -158,7 +158,28 @@ namespace {{packageName}}.Client /// public void AddDefaultHeader(string key, string value) { - _defaultHeaderMap.Add(key, value); + _defaultHeaderMap[key] = value; + } + + /// + /// 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; } /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/FodyWeavers.xml b/modules/swagger-codegen/src/main/resources/csharp/FodyWeavers.xml new file mode 100644 index 00000000000..da017fcbf60 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/FodyWeavers.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache index 7a4c741ca4a..989cedd10ab 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache @@ -31,8 +31,8 @@ limitations under the License. {{packageGuid}} Library Properties - {{packageTitle}} - {{packageTitle}} + {{packageName}} + {{packageName}} {{^supportsUWP}} {{targetFramework}} {{/supportsUWP}} @@ -66,6 +66,7 @@ limitations under the License. + @@ -82,13 +83,19 @@ limitations under the License. ..\..\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll {{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + {{#generatePropertyChanged}} + ..\..\packages\PropertyChanged.Fody.1.51.3\Lib\portable-net4+sl4+wp8+win8+wpa81+MonoAndroid16+MonoTouch40\PropertyChanged.dll + {{/generatePropertyChanged}} + {{#generatePropertyChanged}}{{/generatePropertyChanged}} - + {{#generatePropertyChanged}} + + {{/generatePropertyChanged}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index 77b69c273a4..89af5dd54cc 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -8,7 +8,9 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: {{appVersion}} - SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -24,8 +26,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c {{/supportUWP}} ## 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 +- [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 recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: ``` @@ -68,14 +70,14 @@ namespace Example { {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} - Configuration.Default.Username = 'YOUR_USERNAME'; - Configuration.Default.Password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} - Configuration.Default.ApiKey.Add('{{{keyParamName}}}', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} var apiInstance = new {{classname}}(); @@ -105,6 +107,7 @@ namespace Example }{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` + ## Documentation for API Endpoints All URIs are relative to *{{{basePath}}}* @@ -114,6 +117,7 @@ Class | Method | HTTP request | Description {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + ## Documentation for Models {{#modelPackage}} @@ -126,9 +130,17 @@ No model defined in this package ## Documentation for Authorization -{{^authMethods}} All endpoints do not require authorization. -{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} -{{#authMethods}}### {{name}} +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} {{#isApiKey}}- **Type**: API key - **API key parameter name**: {{keyParamName}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache index f01a7e25dbb..e08b2429864 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache @@ -66,6 +66,7 @@ limitations under the License. + @@ -83,10 +84,10 @@ limitations under the License. {{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll - $(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll - ..\packages\NUnit.3.2.1\lib\nunit.framework.dll - ..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll - {{binRelativePath}}\NUnit.3.2.1\lib\nunit.framework.dll + $(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 + {{binRelativePath}}\NUnit.2.6.4\lib\nunit.framework.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache index c069d7f3dcf..224450867ab 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache @@ -10,6 +10,7 @@ Method | HTTP request | Description {{#operations}} {{#operation}} + # **{{{operationId}}}** > {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -33,14 +34,14 @@ namespace Example { {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} - Configuration.Default.Username = 'YOUR_USERNAME'; - Configuration.Default.Password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} - Configuration.Default.ApiKey.Add('{{{keyParamName}}}', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} var apiInstance = new {{classname}}(); diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache index f3f1caeaf0a..2f20508f336 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache @@ -51,8 +51,8 @@ namespace {{packageName}}.Test [Test] public void {{operationId}}InstanceTest() { - // test 'IsInstanceOfType' {{classname}} - Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}"); + // TODO uncomment below to test 'IsInstanceOfType' {{classname}} + //Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}"); } {{#operations}}{{#operation}} 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 7aab3657090..91b2e83a311 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 @@ -32,6 +32,7 @@ cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/Res echo "[INFO] Run 'mcs' to build bin/{{{packageName}}}.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ +System.ComponentModel.DataAnnotations.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/{{packageName}}.dll \ diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 5da333f4e72..f359175e125 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -14,8 +14,12 @@ @echo off -{{#supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319{{/supportsAsync}} -{{^supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v3.5{{/supportsAsync}} +{{#supportsAsync}} +SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 +{{/supportsAsync}} +{{^supportsAsync}} +SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v3.5 +{{/supportsAsync}} if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://nuget.org/nuget.exe', '.\nuget.exe')" .\nuget.exe install src\{{packageName}}\packages.config -o packages diff --git a/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache b/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache index 56fef626922..d3f4f7b6f55 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache @@ -147,39 +147,39 @@ UpgradeLog*.htm *.swp *.swo - # svn - .svn +# svn +.svn - # SQL Server files - **/App_Data/*.mdf - **/App_Data/*.ldf - **/App_Data/*.sdf +# SQL Server files +**/App_Data/*.mdf +**/App_Data/*.ldf +**/App_Data/*.sdf - #LightSwitch generated files - GeneratedArtifacts/ - _Pvt_Extensions/ - ModelManifest.xml +#LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml - # ========================= - # Windows detritus - # ========================= +# ========================= +# Windows detritus +# ========================= - # Windows image file caches - Thumbs.db - ehthumbs.db +# Windows image file caches +Thumbs.db +ehthumbs.db - # Folder config file - Desktop.ini +# Folder config file +Desktop.ini - # Recycle Bin used on file shares - $RECYCLE.BIN/ +# Recycle Bin used on file shares +$RECYCLE.BIN/ - # Mac desktop service store files - .DS_Store +# Mac desktop service store files +.DS_Store - # SASS Compiler cache - .sass-cache +# SASS Compiler cache +.sass-cache - # Visual Studio 2014 CTP - **/*.sln.ide +# Visual Studio 2014 CTP +**/*.sln.ide diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 863d7ba93ef..9c9610e5326 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -3,12 +3,18 @@ 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; +{{#generatePropertyChanged}} +using PropertyChanged; +using System.ComponentModel; +{{/generatePropertyChanged}} +using System.ComponentModel.DataAnnotations; {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache index ff38385c785..ff007904f46 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache @@ -1,5 +1,5 @@ /// - /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index aaf6df8cf2e..8f0ec47a1fa 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -2,7 +2,10 @@ /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} /// [DataContract] - public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}> + {{#generatePropertyChanged}} + [ImplementPropertyChanged] + {{/generatePropertyChanged}} + public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}>, IValidatableObject { {{#vars}} {{#isEnum}} @@ -169,4 +172,55 @@ this.{{name}} = {{name}}; return hash; } } + +{{#generatePropertyChanged}} + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + +{{/generatePropertyChanged}} + public IEnumerable Validate(ValidationContext validationContext) + { {{#vars}}{{#hasValidation}}{{#maxLength}} + // {{{name}}} ({{{datatype}}}) maxLength + if(this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); + } +{{/maxLength}}{{#minLength}} + // {{{name}}} ({{{datatype}}}) minLength + if(this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); + } +{{/minLength}}{{#maximum}} + // {{{name}}} ({{{datatype}}}) maximum + if(this.{{{name}}} > ({{{datatype}}}){{maximum}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must be a value less than or equal to {{maximum}}.", new [] { "{{{name}}}" }); + } +{{/maximum}}{{#minimum}} + // {{{name}}} ({{{datatype}}}) minimum + if(this.{{{name}}} < ({{{datatype}}}){{minimum}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must be a value greater than or equal to {{minimum}}.", new [] { "{{{name}}}" }); + } +{{/minimum}}{{#pattern}} + // {{{name}}} ({{{datatype}}}) pattern + Regex regex{{{name}}} = new Regex(@"{{vendorExtensions.x-regex}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); + if (false == regex{{{name}}}.Match(this.{{{name}}}).Success) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must match a pattern of {{pattern}}.", new [] { "{{{name}}}" }); + } +{{/pattern}}{{/hasValidation}}{{/vars}} + yield break; + } } diff --git a/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache index b4d1cd74ca6..f985210516f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache @@ -26,8 +26,8 @@ mozroots --import --sync mono nuget.exe install src/{{{packageName}}}.Test/packages.config -o packages echo "[INFO] Install NUnit runners via NuGet" -mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages +mono nuget.exe install NUnit.Runners -Version 2.6.4 -OutputDirectory packages echo "[INFO] Build the solution and run the unit test" xbuild {{{packageName}}}.sln && \ - mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll + mono ./packages/NUnit.Runners.2.6.4/tools/nunit-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache index d9e5dea7d9f..8f82cb7143c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache @@ -2,4 +2,8 @@ + {{#generatePropertyChanged}} + + + {{/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 95192a480bf..7e6f4575391 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache @@ -1,6 +1,6 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache b/modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache new file mode 100644 index 00000000000..518eb901a6f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index cba12208b7d..cff22ffecf9 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -1,38 +1,48 @@ -part of api; +part of {{pubName}}.api; {{#operations}} + class {{classname}} { - String basePath = "{{basePath}}"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - {{classname}}([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + {{classname}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; {{#operation}} /// {{summary}} /// /// {{notes}} - {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} { {{#allParams}}{{^required}} {{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - {{#allParams}} + // verify required params are set - if({{/allParams}}{{#required}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/required}}{{#allParams}}) { - throw new ApiException(400, "missing required params"); - }{{/allParams}} + {{#allParams}} + {{#required}} + if({{paramName}} == null) { + throw new ApiException(400, "Missing required param: {{paramName}}"); + } + {{/required}} + {{/allParams}} // create path and map variables String path = "{{path}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{paramName}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - {{#queryParams}}if("null" != {{paramName}}) - queryParams["{{baseName}}"] = {{paramName}} is List ? {{paramName}}.join(',') : {{paramName}}; + {{#queryParams}} + {{^required}} + if({{paramName}} != null) { + {{/required}} + queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{^required}} + } + {{/required}} {{/queryParams}} {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; {{/headerParams}} @@ -66,17 +76,22 @@ class {{classname}} { {{/formParams}} } - return apiClient.invokeAPI(basePath, path, '{{httpMethod}}', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return {{#returnType}}ApiClient.deserialize(response.body, {{returnBaseType}}){{/returnType}}; - } - else { - return {{#returnType}}null{{/returnType}}; - } - }); + var response = await apiClient.invokeAPI(path, + '{{httpMethod}}', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return {{#returnType}}apiClient.deserialize(response.body, '{{{returnType}}}') as {{{returnType}}} {{/returnType}}; + } else { + return {{#returnType}}null{{/returnType}}; + } } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/dart/apiException.mustache b/modules/swagger-codegen/src/main/resources/dart/apiException.mustache deleted file mode 100644 index c168fb512da..00000000000 --- a/modules/swagger-codegen/src/main/resources/dart/apiException.mustache +++ /dev/null @@ -1,9 +0,0 @@ -part of api; - -class ApiException implements Exception { - int code = 0; - String message = null; - - ApiException(this.code, this.message); - -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index 92fa90d6261..dcbd731d2af 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -1,14 +1,28 @@ -part of api; +part of {{pubName}}.api; + +class QueryParam { + String name; + String value; + + QueryParam(this.name, this.value); +} class ApiClient { - static ApiClient defaultApiClient = new ApiClient(); + + String basePath; + var client = new {{#browserClient}}Browser{{/browserClient}}Client(); Map _defaultHeaderMap = {}; Map _authentications = {}; - static final dson = new Dartson.JSON(); + + final dson = new Dartson.JSON() + ..addTransformer(new DateTimeParser(), DateTime); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - ApiClient() { + final _RegList = new RegExp(r'^List<(.*)>$'); + final _RegMap = new RegExp(r'^Map$'); + + ApiClient({this.basePath: "{{{basePath}}}"}) { // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}} _authentications['{{name}}'] = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} _authentications['{{name}}'] = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} @@ -37,43 +51,55 @@ class ApiClient { } } - static dynamic deserialize(String json, dynamic clazz) { - var result = json; - + dynamic _deserialize(dynamic value, String targetType) { try { - var decodedJson = JSON.decode(json); - - if(decodedJson is List) { - result = []; - for(var obj in decodedJson) { - result.add(_createEntity(obj, clazz)); - } - } else { - result = _createEntity(json, clazz); + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + return value is bool ? value : '$value'.toLowerCase() == 'true'; + case 'double': + return value is double ? value : double.parse('$value'); + {{#models}} + {{#model}} + case '{{classname}}': + return dson.map(value, new {{classname}}()); + {{/model}} + {{/models}} + default: + { + Match match; + if (value is List && + (match = _RegList.firstMatch(targetType)) != null) { + var newTargetType = match[1]; + return value.map((v) => _deserialize(v, newTargetType)).toList(); + } else if (value is Map && + (match = _RegMap.firstMatch(targetType)) != null) { + var newTargetType = match[1]; + return new Map.fromIterables(value.keys, + value.values.map((v) => _deserialize(v, newTargetType))); + } + } } - } on FormatException { - // Just return the passed in value + } catch (e, stack) { + throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack); } - - return result; + throw new ApiException(500, 'Could not find a suitable class for deserialization'); } - static dynamic _createEntity(dynamic json, dynamic clazz) { - bool isMap = json is Map; - - switch(clazz) { - {{#models}} - {{#model}} - case {{classname}}: - return isMap ? dson.map(json, new {{classname}}()) : dson.decode(json, new {{classname}}()); - {{/model}} - {{/models}} - default: - throw new ApiException(500, 'Could not find a suitable class for deserialization'); - } + dynamic deserialize(String json, String targetType) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); + + if (targetType == 'String') return json; + + var decodedJson = JSON.decode(json); + return _deserialize(decodedJson, targetType); } - static String serialize(Object obj) { + String serialize(Object obj) { String serialized = ''; if (obj == null) { serialized = ''; @@ -85,76 +111,61 @@ class ApiClient { return serialized; } - Future invokeAPI( String host, - String path, - String method, - Map queryParams, - Object body, - Map headerParams, - Map formParams, - String contentType, - List authNames) { - - updateParamsForAuth(authNames, queryParams, headerParams); - - var client = new {{#browserClient}}Browser{{/browserClient}}Client(); - - StringBuffer sb = new StringBuffer(); - - for(String key in queryParams.keys) { - String value = queryParams[key]; - if (value != null){ - if(sb.toString().length == 0) { - sb.write("?"); - } else { - sb.write("&"); - } - sb.write(key); - sb.write("="); - sb.write(value); - } - } - String querystring = sb.toString(); + // We don't use a Map for queryParams. + // If collectionFormat is 'multi' a key might appear multiple times. + Future invokeAPI(String path, + String method, + Iterable queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) async { + + _updateParamsForAuth(authNames, queryParams, headerParams); + + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + String queryString = ps.isNotEmpty ? + '?' + ps.join('&') : + ''; - String url = host + path + querystring; + String url = basePath + path + queryString; headerParams.addAll(_defaultHeaderMap); headerParams['Content-Type'] = contentType; - var completer = new Completer(); - if(body is MultipartRequest) { var request = new MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - client.send(request).then((response) => completer.complete(Response.fromStream(response))); + var response = await client.send(request); + return Response.fromStream(response); } else { var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); switch(method) { - case "GET": - return client.get(url, headers: headerParams); case "POST": return client.post(url, headers: headerParams, body: msgBody); case "PUT": return client.put(url, headers: headerParams, body: msgBody); case "DELETE": return client.delete(url, headers: headerParams); + case "PATCH": + return client.patch(url, headers: headerParams, body: msgBody); + default: + return client.get(url, headers: headerParams); } } - - return completer.future; } /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { + void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { authNames.forEach((authName) { Authentication auth = _authentications[authName]; if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); }); } - } diff --git a/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache new file mode 100644 index 00000000000..b86af8d954c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache @@ -0,0 +1,23 @@ +part of {{pubName}}.api; + +class ApiException implements Exception { + int code = 0; + String message = null; + Exception innerException = null; + StackTrace stackTrace = null; + + ApiException(this.code, this.message); + + ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); + + String toString() { + if (message == null) return "ApiException"; + + if (innerException == null) { + return "ApiException $code: $message"; + } + + return "ApiException $code: $message (Inner exception: ${innerException})\n\n" + + stackTrace.toString(); + } +} diff --git a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache new file mode 100644 index 00000000000..6052dfb312b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache @@ -0,0 +1,33 @@ +part of {{pubName}}.api; + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +Iterable _convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = []; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, '$value')); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, '$v')); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 178fe027e39..f608cf214e0 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -1,15 +1,15 @@ -library api; +library {{pubName}}.api; import 'dart:async'; import 'dart:convert';{{#browserClient}} -import 'dart:html'; import 'package:http/browser_client.dart';{{/browserClient}} import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; -import 'package:crypto/crypto.dart'; +import 'package:dartson/transformers/date_time.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; +part 'api_helper.dart'; part 'api_exception.dart'; part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; @@ -20,3 +20,6 @@ part 'auth/http_basic_auth.dart'; {{/apis}}{{/apiInfo}} {{#models}}{{#model}}part 'model/{{classFilename}}.dart'; {{/model}}{{/models}} + +ApiClient defaultApiClient = new ApiClient(); + diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache index 6e728ae916b..7f3ac22ecd8 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class ApiKeyAuth implements Authentication { @@ -10,7 +10,7 @@ class ApiKeyAuth implements Authentication { ApiKeyAuth(this.location, this.paramName); @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = '$apiKeyPrefix $apiKey'; @@ -19,10 +19,9 @@ class ApiKeyAuth implements Authentication { } if (location == 'query' && value != null) { - queryParams[paramName] = value; + queryParams.add(new QueryParam(paramName, value)); } else if (location == 'header' && value != null) { headerParams[paramName] = value; } } - } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache index 4833af90ec0..e7aef188e44 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache @@ -1,7 +1,7 @@ -part of api; +part of {{pubName}}.api; abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(Map queryParams, Map headerParams); + void applyToParams(List queryParams, Map headerParams); } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache index e681c25653d..4fbcb2321b6 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class HttpBasicAuth implements Authentication { @@ -6,9 +6,9 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str)); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache index 5e3e2c8b260..24413b9c3da 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache @@ -1,9 +1,9 @@ -part of api; +part of {{pubName}}.api; class OAuth implements Authentication { @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/model.mustache b/modules/swagger-codegen/src/main/resources/dart/model.mustache index afd72265646..5fe107c7849 100644 --- a/modules/swagger-codegen/src/main/resources/dart/model.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/model.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; {{#models}}{{#model}} @Entity() diff --git a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache index 97bf9c1defd..1167498909e 100644 --- a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache @@ -4,7 +4,6 @@ description: {{pubDescription}} dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - crypto: "^0.9.0" intl: "^0.12.4+2" dev_dependencies: diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache new file mode 100644 index 00000000000..af53effabc7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache @@ -0,0 +1,16 @@ +# Swagger rest server library for Erlang + +## Overview + +An Erlang server stub generated by [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) given an OpenAPI/Swagger spec. + +Dependency: [Cowboy](https://github.com/ninenines/cowboy) + +## Prerequisites + +TODO + +## Getting started + +TODO + diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache new file mode 100644 index 00000000000..355cfad6dae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache @@ -0,0 +1,345 @@ +-module({{packageName}}_api). + +-export([request_params/1]). +-export([request_param_info/2]). +-export([populate_request/3]). +-export([validate_response/4]). + +-type operation_id() :: atom(). +-type request_param() :: atom(). + +-export_type([operation_id/0]). + +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}} +request_params('{{operationId}}') -> + [{{#allParams}}{{^isBodyParam}} + '{{baseName}}'{{/isBodyParam}}{{#isBodyParam}} + '{{dataType}}'{{/isBodyParam}}{{#hasMore}},{{/hasMore}}{{/allParams}} + ]; +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +request_params(_) -> + error(unknown_operation). + +-type rule() :: + {type, 'binary'} | + {type, 'integer'} | + {type, 'float'} | + {type, 'binary'} | + {type, 'boolean'} | + {type, 'date'} | + {type, 'datetime'} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ + source => qs_val | binding | header | body, + rules => [rule()] +}. + +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}}{{#allParams}} +request_param_info('{{operationId}}', {{^isBodyParam}}'{{baseName}}'{{/isBodyParam}}{{#isBodyParam}}'{{dataType}}'{{/isBodyParam}}) -> + #{ + source => {{#isQueryParam}}qs_val{{/isQueryParam}} {{#isPathParam}}binding{{/isPathParam}} {{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}, + rules => [{{#isString}} + {type, 'binary'},{{/isString}}{{#isInteger}} + {type, 'integer'},{{/isInteger}}{{#isLong}} + {type, 'integer'},{{/isLong}}{{#isFloat}} + {type, 'float'},{{/isFloat}}{{#isDouble}} + {type, 'float'},{{/isDouble}}{{#isByteArray}} + {type, 'binary'},{{/isByteArray}}{{#isBinary}} + {type, 'binary'},{{/isBinary}}{{#isBoolean}} + {type, 'boolean'},{{/isBoolean}}{{#isDate}} + {type, 'date'},{{/isDate}}{{#isDateTime}} + {type, 'datetime'},{{/isDateTime}}{{#isEnum}} + {enum, [{{#allowableValues}}{{#values}}'{{.}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] },{{/isEnum}}{{#maximum}} + {max, {{maximum}} }, {{/maximum}}{{#exclusiveMaximum}} + {exclusive_max, {{exclusiveMaximum}} },{{/exclusiveMaximum}}{{#minimum}} + {min, {{minimum}} },{{/minimum}}{{#exclusiveMinimum}} + {exclusive_min, {{exclusiveMinimum}} },{{/exclusiveMinimum}}{{#maxLength}} + {max_length, {{maxLength}} },{{/maxLength}}{{#minLength}} + {min_length, {{minLength}} },{{/minLength}}{{#pattern}} + {pattern, "{{pattern}}" },{{/pattern}}{{#isBodyParam}} + schema,{{/isBodyParam}}{{#required}} + required{{/required}}{{^required}} + not_required{{/required}} + ] + }; +{{/allParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +request_param_info(OperationID, Name) -> + error({unknown_param, OperationID, Name}). + +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state() +) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. + +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +populate_request_params(_, [], Req, _, Model) -> + {ok, Model, Req}; + +populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> + case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of + {ok, K, V, Req} -> + populate_request_params(OperationID, T, Req, ValidatorState, maps:put(K, V, Model)); + Error -> + Error + end. + +populate_request_param(OperationID, Name, Req0, ValidatorState) -> + #{rules := Rules, source := Source} = request_param_info(OperationID, Name), + {Value, Req} = get_value(Source, Name, Req0), + case prepare_param(Rules, Name, Value, ValidatorState) of + {ok, Result} -> {ok, Name, Result, Req}; + {error, Reason} -> + {error, Reason, Req} + end. + +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state() +) -> ok | no_return(). +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}} +{{#responses}} +validate_response('{{operationId}}', {{code}}, Body, ValidatorState) -> + validate_response_body('{{dataType}}', '{{baseType}}', Body, ValidatorState); +{{/responses}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> + [ + validate(schema, ReturnBaseType, Item, ValidatorState) + || Item <- Body]; + +validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> + validate(schema, ReturnBaseType, Body, ValidatorState). + +%%% +validate(Rule = required, Name, Value, _ValidatorState) -> + case Value of + undefined -> validation_error(Rule, Name); + _ -> ok + end; + +validate(not_required, _Name, _Value, _ValidatorState) -> + ok; + +validate(_, _Name, undefined, _ValidatorState) -> + ok; + +validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> + try + {ok, {{packageName}}_utils:to_int(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> + try + {ok, {{packageName}}_utils:to_float(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> + {ok, Value}; + +validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> + V = binary_to_lower(Value), + try + case binary_to_existing_atom(V, utf8) of + B when is_boolean(B) -> {ok, B}; + _ -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> + try + FormattedValue = erlang:binary_to_existing_atom(Value, utf8), + case lists:member(FormattedValue, Values) of + true -> {ok, FormattedValue}; + false -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> + case Value >= Max of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> + case Value > ExclusiveMax of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> + case Value =< Min of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> + case Value =< ExclusiveMin of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> + case size(Value) =< MaxLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> + case size(Value) >= MinLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> + {ok, MP} = re:compile(Pattern), + case re:run(Value, MP) of + {match, _} -> ok; + _ -> validation_error(Rule, Name) + end; + +validate(Rule = schema, Name, Value, ValidatorState) -> + Definition = list_to_binary("#/definitions/" ++ {{packageName}}_utils:to_list(Name)), + try + _ = validate_with_schema(Value, Definition, ValidatorState), + ok + catch + throw:[{schema_invalid, _, Error} | _] -> + Info = #{ + type => schema_invalid, + error => Error + }, + validation_error(Rule, Name, Info); + throw:[{data_invalid, Schema, Error, _, Path} | _] -> + Info = #{ + type => data_invalid, + error => Error, + schema => Schema, + path => Path + }, + validation_error(Rule, Name, Info) + end; + +validate(Rule, Name, _Value, _ValidatorState) -> + error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + error({unknown_validation_rule, Rule}). + +-spec validation_error(Rule :: any(), Name :: any()) -> no_return(). + +validation_error(ViolatedRule, Name) -> + validation_error(ViolatedRule, Name, #{}). + +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). + +validation_error(ViolatedRule, Name, Info) -> + throw({wrong_param, Name, ViolatedRule, Info}). + +get_value(body, _Name, Req0) -> + {ok, Body, Req} = cowboy_req:body(Req0), + Value = prepare_body(Body), + {Value, Req}; + +get_value(qs_val, Name, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_qs(Name), QS), + {Value, Req}; + +get_value(header, Name, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_header(Name), Headers), + {Value, Req}; + +get_value(binding, Name, Req0) -> + {Bindings, Req} = cowboy_req:bindings(Req0), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_binding(Name), Bindings), + {Value, Req}. + +prepare_body(Body) -> + case Body of + <<"">> -> <<"">>; + _ -> jsx:decode(Body, [return_maps]) + end. + +validate_with_schema(Body, Definition, ValidatorState) -> + jesse_schema_validator:validate_with_state( + [{<<"$ref">>, Definition}], + Body, + ValidatorState + ). + +prepare_param(Rules, Name, Value, ValidatorState) -> + try + Result = lists:foldl( + fun(Rule, Acc) -> + case validate(Rule, Name, Acc, ValidatorState) of + ok -> Acc; + {ok, Prepared} -> Prepared + end + end, + Value, + Rules + ), + {ok, Result} + catch + throw:Reason -> + {error, Reason} + end. + +binary_to_lower(V) when is_binary(V) -> + list_to_binary(string:to_lower({{packageName}}_utils:to_list(V))). diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache new file mode 100644 index 00000000000..0bc22f45743 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache @@ -0,0 +1,19 @@ +{application, {{packageName}}, [ + {description, {{#appDescription}}"{{appDescription}}"{{/appDescription}}{{^appDescription}}"Swagger rest server library"{{/appDescription}}}, + {vsn, "{{apiVersion}}"}, + {registered, []}, + {applications, [ + kernel, + stdlib, + ssl, + inets, + jsx, + jesse, + cowboy + ]}, + {env, [ + ]}, + {modules, []}, + {licenses, [{{#licenseInfo}}"{{licenseInfo}}"{{/licenseInfo}}]}, + {links, [{{#infoUrl}}"{{infoUrl}}"{{/infoUrl}}]} +]}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache new file mode 100644 index 00000000000..bf988fac348 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache @@ -0,0 +1,50 @@ +-module({{packageName}}_auth). + +-export([authorize_api_key/5]). + +-spec authorize_api_key( + LogicHandler :: atom(), + OperationID :: {{packageName}}_api:operation_id(), + From :: header | qs_val, + KeyParam :: iodata() | atom(), + Req ::cowboy_req:req() +)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | + {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. + +authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> + {ApiKey, Req} = get_api_key(From, KeyParam, Req0), + case ApiKey of + undefined -> + AuthHeader = <<"">>, + {false, AuthHeader, Req}; + _ -> + Result = {{packageName}}_logic_handler:authorize_api_key( + LogicHandler, + OperationID, + ApiKey + ), + case Result of + {true, Context} -> + {true, Context, Req}; + false -> + AuthHeader = <<"">>, + {false, AuthHeader, Req} + end + end. + +get_api_key(header, KeyParam, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + { + swagger_utils:get_opt( + {{packageName}}_utils:to_header(KeyParam), + Headers + ), + Req + }; + +get_api_key(qs_val, KeyParam, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + { {{packageName}}_utils:get_opt(KeyParam, QS), Req}. + + + diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache new file mode 100644 index 00000000000..3be26911c74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache @@ -0,0 +1,32 @@ +-module({{packageName}}_default_logic_handler). + +-behaviour({{packageName}}_logic_handler). + +-export([handle_request/3]). +{{#authMethods}} + {{#isApiKey}} +-export([authorize_api_key/2]). + {{/isApiKey}} +{{/authMethods}} + +{{#authMethods}} + {{#isApiKey}} +-spec authorize_api_key(OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> {true, #{}}. + +authorize_api_key(_, _) -> {true, #{}}. + {{/isApiKey}} +{{/authMethods}} + +-spec handle_request( + OperationID :: {{packageName}}_api:operation_id(), + Req :: cowboy_req:req(), + Context :: #{} +) -> + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: #{}}. + +handle_request(OperationID, Req, Context) -> + error_logger:error_msg( + "Got not implemented request to process: ~p~n", + [{OperationID, Req, Context}] + ), + {501, [], #{}}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache new file mode 100644 index 00000000000..4559bc2962a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache @@ -0,0 +1,230 @@ +%% basic handler +-module({{classname}}). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: {{packageName}}_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + +{{#operations}}{{#operation}} +allowed_methods( + Req, + State = #state{ + operation_id = '{{operationId}}' + } +) -> + {[<<"{{httpMethod}}">>], Req, State}; +{{/operation}}{{/operations}} +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. +{{#operations}}{{#operation}} +is_authorized( + Req0, + State = #state{ + operation_id = '{{operationId}}' = OperationID, + logic_handler = LogicHandler + } +) -> +{{#authMethods}} + {{#isApiKey}} + From = {{#isKeyInQuery}}qs_val{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}, + Result = {{packageName}}_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "{{keyParamName}}", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + {{/isApiKey}} +{{/authMethods}} +{{/operation}}{{/operations}} +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. +{{#operations}}{{#operation}} +valid_content_headers( + Req0, + State = #state{ + operation_id = '{{operationId}}' + } +) -> + Headers = [{{#headerParams}}"{{baseName}}"{{#hasMore}},{{/hasMore}}{{/headerParams}}], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; +{{/operation}}{{/operations}} +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case {{packageName}}_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = {{packageName}}_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = {{packageName}}_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. 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 new file mode 100644 index 00000000000..cb4ba201bf4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache @@ -0,0 +1,50 @@ +-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(), + Headers :: cowboy:http_headers(), + Body :: #{} +}. + +-export_type([handler_response/0]). + +{{#authMethods}} + {{#isApiKey}} +-callback authorize_api_key( + OperationID :: {{packageName}}_api:operation_id(), + ApiKey :: binary() +) -> + Result :: boolean() | {boolean(), context()}. + {{/isApiKey}} +{{/authMethods}} + + +-callback handle_request(OperationID :: {{packageName}}_api:operation_id(), Request :: any(), Context :: context()) -> + handler_response(). + +-spec handle_request( + Handler :: atom(), + OperationID :: {{packageName}}_api:operation_id(), + Request :: any(), + Context :: context() +) -> + handler_response(). + +handle_request(Handler, OperationID, Req, Context) -> + Handler:handle_request(OperationID, Req, Context). + +{{#authMethods}} + {{#isApiKey}} +-spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> + Result :: false | {true, context()}. +authorize_api_key(Handler, OperationID, ApiKey) -> + Handler:authorize_api_key(OperationID, ApiKey). + {{/isApiKey}} +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache new file mode 100644 index 00000000000..1c7f7d922e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache @@ -0,0 +1,4 @@ +{deps, [ + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "v2.8.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.4.0"}}} +]}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/router.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/router.mustache new file mode 100644 index 00000000000..9c5ff89b229 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/router.mustache @@ -0,0 +1,74 @@ +-module({{packageName}}_router). + +-export([get_paths/1]). + +-type operations() :: #{ + Method :: binary() => {{packageName}}_api:operation_id() +}. + +-type init_opts() :: { + Operations :: operations(), + LogicHandler :: atom(), + ValidatorState :: jesse_state:state() +}. + +-export_type([init_opts/0]). + +-spec get_paths(LogicHandler :: atom()) -> [{'_',[{ + Path :: string(), + Handler :: atom(), + InitOpts :: init_opts() +}]}]. + +get_paths(LogicHandler) -> + ValidatorState = prepare_validator(), + PreparedPaths = maps:fold( + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, + [], + group_paths() + ), + [ + {'_', + [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] + } + ]. + +group_paths() -> + maps:fold( + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, + #{}, + get_operations() + ). + +get_operations() -> + #{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + '{{operationId}}' => #{ + path => "{{basePathWithoutHost}}{{path}}", + method => <<"{{httpMethod}}">>, + handler => '{{classname}}' + }{{#hasMore}},{{/hasMore}}{{/operation}}{{#hasMore}},{{/hasMore}}{{/operations}}{{/apis}}{{/apiInfo}} + }. + +prepare_validator() -> + R = jsx:decode(element(2, file:read_file(get_swagger_path()))), + jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]). + + +get_swagger_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join({{packageName}}_utils:priv_dir(AppName), "swagger.json"). + + diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache new file mode 100644 index 00000000000..90a6388ea5d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache @@ -0,0 +1,64 @@ +-module({{packageName}}_server). + + +-define(DEFAULT_ACCEPTORS_POOLSIZE, 100). +-define(DEFAULT_LOGIC_HANDLER, {{packageName}}_default_logic_handler). + +-export([child_spec/2]). + +-spec child_spec( ID :: any(), #{ + ip => inet:ip_address(), + port => inet:port_number(), + net_opts => [] +}) -> supervisor:child_spec(). + +child_spec(ID, #{ + ip := IP , + port := Port, + net_opts := NetOpts +} = Params) -> + AcceptorsPool = ?DEFAULT_ACCEPTORS_POOLSIZE, + {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), + LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), + ExtraOpts = maps:get(cowboy_extra_opts, Params, []), + CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + ranch:child_spec({?MODULE, ID}, AcceptorsPool, + Transport, TransportOpts, cowboy_protocol, CowboyOpts). + +get_socket_transport(IP, Port, Options) -> + Opts = [ + {ip, IP}, + {port, Port} + ], + case {{packageName}}_utils:get_opt(ssl, Options) of + SslOpts = [_|_] -> + {ranch_ssl, Opts ++ SslOpts}; + undefined -> + {ranch_tcp, Opts} + end. + +get_cowboy_config(LogicHandler, ExtraOpts) -> + get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). + +get_cowboy_config(_LogicHandler, [], Opts) -> + Opts; + +get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> + NewEnv = case proplists:get_value(dispatch, Env) of + undefined -> [get_default_dispatch(LogicHandler) | Env]; + _ -> Env + end, + get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); + +get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> + get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). + +get_default_dispatch(LogicHandler) -> + Paths = {{packageName}}_router:get_paths(LogicHandler), + {dispatch, cowboy_router:compile(Paths)}. + +get_default_opts(LogicHandler) -> + [{env, [get_default_dispatch(LogicHandler)]}]. + +store_key(Key, Value, Opts) -> + lists:keystore(Key, 1, Opts, {Key, Value}). diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache new file mode 100644 index 00000000000..9bf6bbcffba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-json}}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache new file mode 100644 index 00000000000..b6701add7fc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache @@ -0,0 +1,173 @@ +-module({{packageName}}_utils). + +-export([to_binary/1]). +-export([to_list/1]). +-export([to_float/1]). +-export([to_int/1]). +-export([to_lower/1]). +-export([to_upper/1]). +-export([set_resp_headers/2]). +-export([to_header/1]). +-export([to_qs/1]). +-export([to_binding/1]). +-export([get_opt/2]). +-export([get_opt/3]). +-export([priv_dir/0]). +-export([priv_dir/1]). +-export([priv_path/1]). + + +-spec to_binary(iodata() | atom() | number()) -> binary(). + +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> string(). + +to_list(V) when is_list(V) -> V; +to_list(V) -> binary_to_list(to_binary(V)). + +-spec to_float(iodata()) -> number(). + +to_float(V) -> + Data = iolist_to_binary([V]), + case binary:split(Data, <<$.>>) of + [Data] -> + binary_to_integer(Data); + [<<>>, _] -> + binary_to_float(<<$0, Data/binary>>); + _ -> + binary_to_float(Data) + end. + +%% + +-spec to_int(integer() | binary() | list()) -> integer(). + +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). + +set_resp_headers([], Req) -> + Req; +set_resp_headers([{K, V} | T], Req0) -> + Req = cowboy_req:set_resp_header(K, V, Req0), + set_resp_headers(T, Req). + +-spec to_header(iodata() | atom() | number()) -> binary(). + +to_header(Name) -> + Prepared = to_binary(Name), + to_lower(Prepared). + +-spec to_qs(iodata() | atom() | number()) -> binary(). + +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). + +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). + +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). + +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +-spec priv_dir() -> file:filename(). + +priv_dir() -> + {ok, AppName} = application:get_application(), + priv_dir(AppName). + +-spec priv_dir(Application :: atom()) -> file:filename(). + +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +-spec priv_path(Relative :: file:filename()) -> file:filename(). + +priv_path(Relative) -> + filename:join(priv_dir(), Relative). + +-include_lib("kernel/include/file.hrl"). + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. + + +%% + +-spec to_lower(binary()) -> binary(). + +to_lower(S) -> + to_case(lower, S, <<>>). + +-spec to_upper(binary()) -> binary(). + +to_upper(S) -> + to_case(upper, S, <<>>). + +to_case(_Case, <<>>, Acc) -> + Acc; + +to_case(_Case, <>, _Acc) when C > 127 -> + error(badarg); + +to_case(Case = lower, <>, Acc) -> + to_case(Case, Rest, <>); + +to_case(Case = upper, <>, Acc) -> + to_case(Case, Rest, <>). + +to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> + C + 32; +to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> + C + 32; +to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> + C + 32; +to_lower_char(C) -> + C. + +to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> + C - 32; +to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> + C - 32; +to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> + C - 32; +to_upper_char(C) -> + C. diff --git a/modules/swagger-codegen/src/main/resources/flash/Response.as b/modules/swagger-codegen/src/main/resources/flash/Response.as index a43b7980a38..d19dd0ae358 100644 --- a/modules/swagger-codegen/src/main/resources/flash/Response.as +++ b/modules/swagger-codegen/src/main/resources/flash/Response.as @@ -12,7 +12,7 @@ public class Response { public var isSuccess:Boolean; /** - * The payload of the succesful operation eg. a Word in a WordRequest + * The payload of the successful operation eg. a Word in a WordRequest */ public var payload:Object; diff --git a/modules/swagger-codegen/src/main/resources/flash/build.properties b/modules/swagger-codegen/src/main/resources/flash/build.properties index 8e77d88c961..356f112b144 100644 --- a/modules/swagger-codegen/src/main/resources/flash/build.properties +++ b/modules/swagger-codegen/src/main/resources/flash/build.properties @@ -4,7 +4,7 @@ title=Sample app AS3 SDK API Documentation #Path to the source folder where the .as files are located sourcepath = ./src/main/flex -# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ ) +# Class-folders you want to search for classes to be included in the docs, separated by spaces (for example ../com/ ../net/ ) # to include every .as and .mxml file within your project, just state ../ domainextensions = ./src/main/flex diff --git a/modules/swagger-codegen/src/main/resources/flash/build.xml b/modules/swagger-codegen/src/main/resources/flash/build.xml index 4f021b0b8b2..9b84a466b76 100644 --- a/modules/swagger-codegen/src/main/resources/flash/build.xml +++ b/modules/swagger-codegen/src/main/resources/flash/build.xml @@ -17,7 +17,7 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache index cc7805c9b97..d53139b49b2 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -10,8 +10,14 @@ This example uses the [Connexion](https://github.com/zalando/connexion) library To run the server, please execute the following: ``` +{{#supportPython2}} +sudo pip install -U connexion # install Connexion from PyPI +python app.py +{{/supportPython2}} +{{^supportPython2}} sudo pip3 install -U connexion # install Connexion from PyPI python3 app.py +{{/supportPython2}} ``` and open your browser to here: diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache index ded223fb36d..85fd9a354f1 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache @@ -1,4 +1,9 @@ +{{#supportPython2}} +#!/usr/bin/env python +{{/supportPython2}} +{{^supportPython2}} #!/usr/bin/env python3 +{{/supportPython2}} import connexion diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache index e9167e5bfe8..8050f04ba51 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache @@ -1,5 +1,3 @@ -{{#apiInfo}} -{{#apis}} {{#operations}} {{#operation}} @@ -7,5 +5,3 @@ def {{operationId}}({{#allParams}}{{paramName}}{{^required}} = None{{/required}} return 'do some magic!' {{/operation}} {{/operations}} -{{/apis}} -{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/go-server/routers.mustache b/modules/swagger-codegen/src/main/resources/go-server/routers.mustache index 5999268a528..9242b2084a0 100644 --- a/modules/swagger-codegen/src/main/resources/go-server/routers.mustache +++ b/modules/swagger-codegen/src/main/resources/go-server/routers.mustache @@ -40,14 +40,14 @@ var routes = Routes{ Route{ "Index", "GET", - "/", + "{{basePathWithoutHost}}/", Index, }, {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} Route{ "{{operationId}}", "{{httpMethod}}", - "{{path}}", + "{{basePathWithoutHost}}{{path}}", {{operationId}}, }, {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/go/README.mustache b/modules/swagger-codegen/src/main/resources/go/README.mustache index 026d0648ea6..0cfe5bfcae3 100644 --- a/modules/swagger-codegen/src/main/resources/go/README.mustache +++ b/modules/swagger-codegen/src/main/resources/go/README.mustache @@ -9,7 +9,9 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: {{appVersion}} - Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index b3e2f6db9af..ef388bcf278 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -3,22 +3,20 @@ package {{packageName}} {{#operations}} import ( - "strings" - "fmt" - "errors" "net/url" - {{#imports}}"{{import}}" + "strings" +{{#imports}} "{{import}}" {{/imports}} ) type {{classname}} struct { - Configuration Configuration + Configuration *Configuration } func New{{classname}}() *{{classname}} { configuration := NewConfiguration() return &{{classname}}{ - Configuration: *configuration, + Configuration: configuration, } } @@ -27,7 +25,7 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}} { configuration.BasePath = basePath return &{{classname}}{ - Configuration: *configuration, + Configuration: configuration, } } {{#operation}} @@ -39,44 +37,47 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}} { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ -func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { +func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { - var httpMethod = "{{httpMethod}}" + var localVarHttpMethod = strings.ToUpper("{{httpMethod}}") // create path and map variables - path := a.Configuration.BasePath + "{{path}}"{{#pathParams}} - path = strings.Replace(path, "{"+"{{baseName}}"+"}", fmt.Sprintf("%v", {{paramName}}), -1){{/pathParams}} -{{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if &{{paramName}} == nil { - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}new({{{returnType}}}), {{/returnType}}nil, errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") - }{{/required}}{{/allParams}} + localVarPath := a.Configuration.BasePath + "{{path}}"{{#pathParams}} + localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", fmt.Sprintf("%v", {{paramName}}), -1){{/pathParams}} - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte {{#authMethods}} - // authentication ({{name}}) required -{{#isApiKey}}{{#isKeyInHeader}} + // authentication '({{name}})' required +{{#isApiKey}} +{{#isKeyInHeader}} // set key with prefix in header - headerParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") -{{/isKeyInHeader}}{{#isKeyInQuery}} - // set key with prefix in querystring{{#hasKeyParamName}} - queryParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") -{{/hasKeyParamName}}{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} + localVarHeaderParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") +{{/isKeyInHeader}} +{{#isKeyInQuery}} + // set key with prefix in query string + localVarQueryParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") +{{/isKeyInQuery}} +{{/isApiKey}} +{{#isBasic}} // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - headerParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - }{{/isBasic}}{{#isOAuth}} + if a.Configuration.UserName != "" || a.Configuration.Password != ""{ + localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() + } +{{/isBasic}} +{{#isOAuth}} // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - }{{/isOAuth}}{{/authMethods}} + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + } +{{/isOAuth}} +{{/authMethods}} // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } {{#hasQueryParams}} {{#queryParams}} @@ -84,16 +85,17 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ var collectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}" if collectionFormat == "multi" { for _, value := range {{paramName}} { - queryParams.Add("{{paramName}}", value) + localVarQueryParams.Add("{{baseName}}", value) } } else { - queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) + localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) } {{/isListContainer}} {{^isListContainer}} - queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) + localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) {{/isListContainer}} - {{/queryParams}}{{/hasQueryParams}} + {{/queryParams}} + {{/hasQueryParams}} // to determine the Content-Type header localVarHttpContentTypes := []string{ {{#consumes}}"{{{mediaType}}}", {{/consumes}} } @@ -101,37 +103,62 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ - {{#produces}}"{{{mediaType}}}", -{{/produces}} } + {{#produces}} + "{{{mediaType}}}", + {{/produces}} + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept - }{{#hasHeaderParams}} - -{{#headerParams}} // header params "{{baseName}}" - headerParams["{{baseName}}"] = {{paramName}} -{{/headerParams}}{{/hasHeaderParams}}{{#hasFormParams}} -{{#formParams}}{{#isFile}} + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } +{{#hasHeaderParams}} +{{#headerParams}} + // header params "{{baseName}}" + localVarHeaderParams["{{baseName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}}, "") +{{/headerParams}} +{{/hasHeaderParams}} +{{#hasFormParams}} +{{#formParams}} +{{#isFile}} fbs, _ := ioutil.ReadAll(file) - fileBytes = fbs - fileName = file.Name(){{/isFile}} -{{^isFile}} formParams["{{paramName}}"] = {{paramName}}{{/isFile}}{{/formParams}}{{/hasFormParams}}{{#hasBodyParam}} + localVarFileBytes = fbs + localVarFileName = file.Name() +{{/isFile}} +{{^isFile}} + localVarFormParams["{{paramName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}}, "") +{{/isFile}} +{{/formParams}} +{{/hasFormParams}} +{{#hasBodyParam}} {{#bodyParams}} // body params - postBody = &{{paramName}} -{{/bodyParams}}{{/hasBodyParam}} -{{#returnType}} var successPayload = new({{returnType}}){{/returnType}} - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarPostBody = &{{paramName}} +{{/bodyParams}} +{{/hasBodyParam}} +{{#returnType}} + var successPayload = new({{returnType}}) +{{/returnType}} + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "{{operationId}}", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}NewAPIResponse(httpResponse.RawResponse), err + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}localVarAPIResponse, err } {{#returnType}} - err = json.Unmarshal(httpResponse.Body(), &successPayload){{/returnType}} - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) +{{/returnType}} + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}localVarAPIResponse, err } {{/operation}}{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/go/api_client.mustache b/modules/swagger-codegen/src/main/resources/go/api_client.mustache index be0f60673d8..a92c7631202 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_client.mustache @@ -8,10 +8,12 @@ import ( "reflect" "strings" "net/url" + "io/ioutil" "github.com/go-resty/resty" ) type APIClient struct { + config *Configuration } func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { @@ -36,9 +38,9 @@ func (c *APIClient) SelectHeaderAccept(accepts []string) string { return strings.Join(accepts, ",") } -func contains(source []string, containvalue string) bool { - for _, a := range source { - if strings.ToLower(a) == strings.ToLower(containvalue) { +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { return true } } @@ -53,11 +55,8 @@ func (c *APIClient) CallAPI(path string, method string, fileName string, fileBytes []byte) (*resty.Response, error) { - //set debug flag - configuration := NewConfiguration() - resty.SetDebug(configuration.GetDebug()) - - request := prepareRequest(postBody, headerParams, queryParams, formParams, fileName, fileBytes) + rClient := c.prepareClient() + request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) switch strings.ToUpper(method) { case "GET": @@ -94,19 +93,42 @@ func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) s } } - return obj.(string) + return fmt.Sprintf("%v", obj) +} + +func (c *APIClient) prepareClient() *resty.Client { + + rClient := resty.New() + + rClient.SetDebug(c.config.Debug) + if c.config.Transport != nil { + rClient.SetTransport(c.config.Transport) + } + + if c.config.Timeout != nil { + rClient.SetTimeout(*c.config.Timeout) + } + rClient.SetLogger(ioutil.Discard) + return rClient } -func prepareRequest(postBody interface{}, +func (c *APIClient) prepareRequest( + rClient *resty.Client, + postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams map[string]string, fileName string, fileBytes []byte) *resty.Request { - request := resty.R() + + request := rClient.R() request.SetBody(postBody) + if c.config.UserAgent != "" { + request.SetHeader("User-Agent", c.config.UserAgent) + } + // add header parameter, if any if len(headerParams) > 0 { request.SetHeaders(headerParams) diff --git a/modules/swagger-codegen/src/main/resources/go/api_response.mustache b/modules/swagger-codegen/src/main/resources/go/api_response.mustache index 9bacc9578e4..00ab14a5124 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_response.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_response.mustache @@ -6,8 +6,20 @@ import ( ) type APIResponse struct { - *http.Response + *http.Response `json:"-"` Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { diff --git a/modules/swagger-codegen/src/main/resources/go/configuration.mustache b/modules/swagger-codegen/src/main/resources/go/configuration.mustache index fbc22f603d0..6f56b2138fb 100644 --- a/modules/swagger-codegen/src/main/resources/go/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/go/configuration.mustache @@ -3,36 +3,42 @@ package {{packageName}} import ( "encoding/base64" + "net/http" + "time" ) + type Configuration struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` APIKey map[string]string `json:"APIKey,omitempty"` - debug bool `json:"debug,omitempty"` + Debug bool `json:"debug,omitempty"` DebugFile string `json:"debugFile,omitempty"` OAuthToken string `json:"oAuthToken,omitempty"` - Timeout int `json:"timeout,omitempty"` BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` AccessToken string `json:"accessToken,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` - APIClient APIClient `json:"APIClient,omitempty"` + APIClient *APIClient + Transport *http.Transport + Timeout *time.Duration `json:"timeout,omitempty"` } func NewConfiguration() *Configuration { - return &Configuration{ - BasePath: "{{basePath}}", - UserName: "", - debug: false, + cfg := &Configuration{ + BasePath: "{{{basePath}}}", DefaultHeader: make(map[string]string), APIKey: make(map[string]string), APIKeyPrefix: make(map[string]string), UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/go{{/httpUserAgent}}", + APIClient: &APIClient{}, } + + cfg.APIClient.config = cfg + return cfg } func (c *Configuration) GetBasicAuthEncodedString() string { @@ -50,11 +56,3 @@ func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { return c.APIKey[APIKeyIdentifier] } - -func (c *Configuration) SetDebug(enable bool) { - c.debug = enable -} - -func (c *Configuration) GetDebug() bool { - return c.debug -} diff --git a/modules/swagger-codegen/src/main/resources/go/pom.mustache b/modules/swagger-codegen/src/main/resources/go/pom.mustache deleted file mode 100644 index 5cfbc0428c3..00000000000 --- a/modules/swagger-codegen/src/main/resources/go/pom.mustache +++ /dev/null @@ -1,75 +0,0 @@ - - 4.0.0 - com.wordnik - Go{{packageName}} - pom - {{packageVersion}} - Go{{packageName}} - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - go-get-testify - pre-integration-test - - exec - - - go - - get - github.com/stretchr/testify/assert - - - - - go-get-sling - pre-integration-test - - exec - - - go - - get - github.com/dghubble/sling - - - - - go-test - integration-test - - exec - - - go - - test - -v - - - - - - - - \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index b94414d5b26..d3c2681bced 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -28,23 +28,25 @@ [ Jump to Models ] {{! for the tables of content, I cheat and don't use CSS styles.... }} -

Table of Contents

+

Table of Contents

{{access}}
{{#apiInfo}} -
    {{#apis}} {{#operations}} +

    {{baseName}}

    + {{/operations}} {{/apis}} -
{{/apiInfo}} {{#apiInfo}} {{#apis}} {{#operations}} +

{{baseName}}

{{#operation}}
@@ -78,12 +80,12 @@
{{/hasBodyParam}} - {{#hasHeaderParam}} + {{#hasHeaderParams}}

Request headers

{{#headerParam}}{{>headerParam}}{{/headerParam}}
- {{/hasHeaderParam}} + {{/hasHeaderParams}} {{#hasQueryParams}}

Query parameters

@@ -150,7 +152,7 @@

Models

[ Jump to Methods ] -

Table of Contents

+

Table of Contents

    {{#models}} {{#model}} @@ -162,7 +164,8 @@ {{#models}} {{#model}}
    -

    {{name}} Up

    +

    {{name}} - {{title}} Up

    +
    {{description}}
    {{#vars}}
    {{name}} {{^required}}(optional){{/required}}
    {{^isPrimitiveType}}{{datatype}}{{/isPrimitiveType}} {{description}} {{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
    {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache index 8d9a5755d7b..04eccf69491 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -1,4 +1,4 @@ -body { +body { font-family: Trebuchet MS, sans-serif; font-size: 15px; color: #444; @@ -20,7 +20,6 @@ hr { border: 0; color: #ddd; background-color: #ddd; - display: none; } .app-desc { @@ -170,4 +169,4 @@ font-style: italic; color: #FFF; display: inline-block; text-decoration: none; -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache new file mode 100644 index 00000000000..f84ec4773fd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache @@ -0,0 +1,10 @@ + +/*! + * Bootstrap v2.3.2 + * + * Copyright 2013 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world by @mdo and @fat. + */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}a{color:#08c;text-decoration:none}a:hover,a:focus{color:#005580;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}[class*="span"].hide,.row-fluid [class*="span"].hide{display:none}[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right}.container{margin-right:auto;margin-left:auto;*zoom:1}.container:before,.container:after{display:table;line-height:0;content:""}.container:after{clear:both}.container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.container-fluid:before,.container-fluid:after{display:table;line-height:0;content:""}.container-fluid:after{clear:both}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}small{font-size:85%}strong{font-weight:bold}em{font-style:italic}cite{font-style:normal}.muted{color:#999}a.muted:hover,a.muted:focus{color:#808080}.text-warning{color:#c09853}a.text-warning:hover,a.text-warning:focus{color:#a47e3c}.text-error{color:#b94a48}a.text-error:hover,a.text-error:focus{color:#953b39}.text-info{color:#3a87ad}a.text-info:hover,a.text-info:focus{color:#2d6987}.text-success{color:#468847}a.text-success:hover,a.text-success:focus{color:#356635}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{line-height:40px}h1{font-size:38.5px}h2{font-size:31.5px}h3{font-size:24.5px}h4{font-size:17.5px}h5{font-size:14px}h6{font-size:11.9px}h1 small{font-size:24.5px}h2 small{font-size:17.5px}h3 small{font-size:14px}h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}ul,ol{padding:0;margin:0 0 10px 25px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}li{line-height:20px}ul.unstyled,ol.unstyled{margin-left:0;list-style:none}ul.inline,ol.inline{margin-left:0;list-style:none}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}dl{margin-bottom:20px}dt,dd{line-height:20px}dt{font-weight:bold}dd{margin-left:10px}.dl-horizontal{*zoom:1}.dl-horizontal:before,.dl-horizontal:after{display:table;line-height:0;content:""}.dl-horizontal:after{clear:both}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}blockquote small{display:block;line-height:20px;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}form{margin:0 0 20px}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5}legend small{font-size:15px;color:#999}label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px}input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif}label{display:block;margin-bottom:5px}select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,.uneditable-input{width:206px}textarea{height:auto}textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto}select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px}select{width:220px;background-color:#fff;border:1px solid #ccc}select[multiple],select[size]{height:auto}select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.uneditable-input,.uneditable-textarea{color:#999;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.uneditable-input{overflow:hidden;white-space:nowrap}.uneditable-textarea{width:auto;height:auto}input:-moz-placeholder,textarea:-moz-placeholder{color:#999}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999}.radio,.checkbox{min-height:20px;padding-left:20px}.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px}.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px}.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px}.input-mini{width:60px}.input-small{width:90px}.input-medium{width:150px}.input-large{width:210px}.input-xlarge{width:270px}.input-xxlarge{width:530px}input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:926px}input.span11,textarea.span11,.uneditable-input.span11{width:846px}input.span10,textarea.span10,.uneditable-input.span10{width:766px}input.span9,textarea.span9,.uneditable-input.span9{width:686px}input.span8,textarea.span8,.uneditable-input.span8{width:606px}input.span7,textarea.span7,.uneditable-input.span7{width:526px}input.span6,textarea.span6,.uneditable-input.span6{width:446px}input.span5,textarea.span5,.uneditable-input.span5{width:366px}input.span4,textarea.span4,.uneditable-input.span4{width:286px}input.span3,textarea.span3,.uneditable-input.span3{width:206px}input.span2,textarea.span2,.uneditable-input.span2{width:126px}input.span1,textarea.span1,.uneditable-input.span1{width:46px}.controls-row{*zoom:1}.controls-row:before,.controls-row:after{display:table;line-height:0;content:""}.controls-row:after{clear:both}.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left}.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px}input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eee}input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent}.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853}.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853}.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48}.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48}.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847}.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847}.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad}.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad}.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1}.form-actions:before,.form-actions:after{display:table;line-height:0;content:""}.form-actions:after{clear:both}.help-block,.help-inline{color:#595959}.help-block{display:block;margin-bottom:10px}.help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.input-append,.input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2}.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546}.input-prepend .add-on,.input-prepend .btn{margin-right:-1px}.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px}.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .btn-group:first-child{margin-left:0}input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none}.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block}.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0}.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.control-group{margin-bottom:10px}legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.form-horizontal .control-group{margin-bottom:20px;*zoom:1}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;line-height:0;content:""}.form-horizontal .control-group:after{clear:both}.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.form-horizontal .controls:first-child{*padding-left:180px}.form-horizontal .help-block{margin-bottom:0}.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px}.form-horizontal .form-actions{padding-left:180px}table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.table{width:100%;margin-bottom:20px}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.table th{font-weight:bold}.table thead th{vertical-align:bottom}.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed th,.table-condensed td{padding:4px 5px}.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.table-bordered th,.table-bordered td{border-left:1px solid #ddd}.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0}.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5}table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.table td.span1,.table th.span1{float:none;width:44px;margin-left:0}.table td.span2,.table th.span2{float:none;width:124px;margin-left:0}.table td.span3,.table th.span3{float:none;width:204px;margin-left:0}.table td.span4,.table th.span4{float:none;width:284px;margin-left:0}.table td.span5,.table th.span5{float:none;width:364px;margin-left:0}.table td.span6,.table th.span6{float:none;width:444px;margin-left:0}.table td.span7,.table th.span7{float:none;width:524px;margin-left:0}.table td.span8,.table th.span8{float:none;width:604px;margin-left:0}.table td.span9,.table th.span9{float:none;width:684px;margin-left:0}.table td.span10,.table th.span10{float:none;width:764px;margin-left:0}.table td.span11,.table th.span11{float:none;width:844px;margin-left:0}.table td.span12,.table th.span12{float:none;width:924px;margin-left:0}.table tbody tr.success>td{background-color:#dff0d8}.table tbody tr.error>td{background-color:#f2dede}.table tbody tr.warning>td{background-color:#fcf8e3}.table tbody tr.info>td{background-color:#d9edf7}.table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.table-hover tbody tr.error:hover>td{background-color:#ebcccc}.table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.table-hover tbody tr.info:hover>td{background-color:#c4e3f3}[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.icon-glass{background-position:0 0}.icon-music{background-position:-24px 0}.icon-search{background-position:-48px 0}.icon-envelope{background-position:-72px 0}.icon-heart{background-position:-96px 0}.icon-star{background-position:-120px 0}.icon-star-empty{background-position:-144px 0}.icon-user{background-position:-168px 0}.icon-film{background-position:-192px 0}.icon-th-large{background-position:-216px 0}.icon-th{background-position:-240px 0}.icon-th-list{background-position:-264px 0}.icon-ok{background-position:-288px 0}.icon-remove{background-position:-312px 0}.icon-zoom-in{background-position:-336px 0}.icon-zoom-out{background-position:-360px 0}.icon-off{background-position:-384px 0}.icon-signal{background-position:-408px 0}.icon-cog{background-position:-432px 0}.icon-trash{background-position:-456px 0}.icon-home{background-position:0 -24px}.icon-file{background-position:-24px -24px}.icon-time{background-position:-48px -24px}.icon-road{background-position:-72px -24px}.icon-download-alt{background-position:-96px -24px}.icon-download{background-position:-120px -24px}.icon-upload{background-position:-144px -24px}.icon-inbox{background-position:-168px -24px}.icon-play-circle{background-position:-192px -24px}.icon-repeat{background-position:-216px -24px}.icon-refresh{background-position:-240px -24px}.icon-list-alt{background-position:-264px -24px}.icon-lock{background-position:-287px -24px}.icon-flag{background-position:-312px -24px}.icon-headphones{background-position:-336px -24px}.icon-volume-off{background-position:-360px -24px}.icon-volume-down{background-position:-384px -24px}.icon-volume-up{background-position:-408px -24px}.icon-qrcode{background-position:-432px -24px}.icon-barcode{background-position:-456px -24px}.icon-tag{background-position:0 -48px}.icon-tags{background-position:-25px -48px}.icon-book{background-position:-48px -48px}.icon-bookmark{background-position:-72px -48px}.icon-print{background-position:-96px -48px}.icon-camera{background-position:-120px -48px}.icon-font{background-position:-144px -48px}.icon-bold{background-position:-167px -48px}.icon-italic{background-position:-192px -48px}.icon-text-height{background-position:-216px -48px}.icon-text-width{background-position:-240px -48px}.icon-align-left{background-position:-264px -48px}.icon-align-center{background-position:-288px -48px}.icon-align-right{background-position:-312px -48px}.icon-align-justify{background-position:-336px -48px}.icon-list{background-position:-360px -48px}.icon-indent-left{background-position:-384px -48px}.icon-indent-right{background-position:-408px -48px}.icon-facetime-video{background-position:-432px -48px}.icon-picture{background-position:-456px -48px}.icon-pencil{background-position:0 -72px}.icon-map-marker{background-position:-24px -72px}.icon-adjust{background-position:-48px -72px}.icon-tint{background-position:-72px -72px}.icon-edit{background-position:-96px -72px}.icon-share{background-position:-120px -72px}.icon-check{background-position:-144px -72px}.icon-move{background-position:-168px -72px}.icon-step-backward{background-position:-192px -72px}.icon-fast-backward{background-position:-216px -72px}.icon-backward{background-position:-240px -72px}.icon-play{background-position:-264px -72px}.icon-pause{background-position:-288px -72px}.icon-stop{background-position:-312px -72px}.icon-forward{background-position:-336px -72px}.icon-fast-forward{background-position:-360px -72px}.icon-step-forward{background-position:-384px -72px}.icon-eject{background-position:-408px -72px}.icon-chevron-left{background-position:-432px -72px}.icon-chevron-right{background-position:-456px -72px}.icon-plus-sign{background-position:0 -96px}.icon-minus-sign{background-position:-24px -96px}.icon-remove-sign{background-position:-48px -96px}.icon-ok-sign{background-position:-72px -96px}.icon-question-sign{background-position:-96px -96px}.icon-info-sign{background-position:-120px -96px}.icon-screenshot{background-position:-144px -96px}.icon-remove-circle{background-position:-168px -96px}.icon-ok-circle{background-position:-192px -96px}.icon-ban-circle{background-position:-216px -96px}.icon-arrow-left{background-position:-240px -96px}.icon-arrow-right{background-position:-264px -96px}.icon-arrow-up{background-position:-289px -96px}.icon-arrow-down{background-position:-312px -96px}.icon-share-alt{background-position:-336px -96px}.icon-resize-full{background-position:-360px -96px}.icon-resize-small{background-position:-384px -96px}.icon-plus{background-position:-408px -96px}.icon-minus{background-position:-433px -96px}.icon-asterisk{background-position:-456px -96px}.icon-exclamation-sign{background-position:0 -120px}.icon-gift{background-position:-24px -120px}.icon-leaf{background-position:-48px -120px}.icon-fire{background-position:-72px -120px}.icon-eye-open{background-position:-96px -120px}.icon-eye-close{background-position:-120px -120px}.icon-warning-sign{background-position:-144px -120px}.icon-plane{background-position:-168px -120px}.icon-calendar{background-position:-192px -120px}.icon-random{width:16px;background-position:-216px -120px}.icon-comment{background-position:-240px -120px}.icon-magnet{background-position:-264px -120px}.icon-chevron-up{background-position:-288px -120px}.icon-chevron-down{background-position:-313px -119px}.icon-retweet{background-position:-336px -120px}.icon-shopping-cart{background-position:-360px -120px}.icon-folder-close{width:16px;background-position:-384px -120px}.icon-folder-open{width:16px;background-position:-408px -120px}.icon-resize-vertical{background-position:-432px -119px}.icon-resize-horizontal{background-position:-456px -118px}.icon-hdd{background-position:0 -144px}.icon-bullhorn{background-position:-24px -144px}.icon-bell{background-position:-48px -144px}.icon-certificate{background-position:-72px -144px}.icon-thumbs-up{background-position:-96px -144px}.icon-thumbs-down{background-position:-120px -144px}.icon-hand-right{background-position:-144px -144px}.icon-hand-left{background-position:-168px -144px}.icon-hand-up{background-position:-192px -144px}.icon-hand-down{background-position:-216px -144px}.icon-circle-arrow-right{background-position:-240px -144px}.icon-circle-arrow-left{background-position:-264px -144px}.icon-circle-arrow-up{background-position:-288px -144px}.icon-circle-arrow-down{background-position:-312px -144px}.icon-globe{background-position:-336px -144px}.icon-wrench{background-position:-360px -144px}.icon-tasks{background-position:-384px -144px}.icon-filter{background-position:-408px -144px}.icon-briefcase{background-position:-432px -144px}.icon-fullscreen{background-position:-456px -144px}.dropup,.dropdown{position:relative}.dropdown-toggle{*margin-bottom:-3px}.dropdown-toggle:active,.open .dropdown-toggle{outline:0}.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown .caret{margin-top:8px;margin-left:2px}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open{*z-index:1000}.open>.dropdown-menu{display:block}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.dropdown-submenu{position:relative}.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.dropdown-submenu:hover>.dropdown-menu{display:block}.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.dropdown-submenu:hover>a:after{border-left-color:#fff}.dropdown-submenu.pull-left{float:none}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.collapse.in{height:auto}.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#333;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #ccc;*border:0;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;*background-color:#04c;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;*background-color:#f89406;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;*background-color:#bd362f;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;*background-color:#51a351;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;*background-color:#2f96b4;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;*background-color:#222;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{color:#08c;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.btn-group:first-child{*margin-left:0}.btn-group+.btn-group{margin-left:5px}.btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px}.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group>.btn+.btn{margin-left:-1px}.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px}.btn-group>.btn-mini{font-size:10.5px}.btn-group>.btn-small{font-size:11.9px}.btn-group>.btn-large{font-size:17.5px}.btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.btn-group.open .btn-primary.dropdown-toggle{background-color:#04c}.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406}.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f}.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351}.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4}.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222}.btn .caret{margin-top:8px;margin-left:0}.btn-large .caret{margin-top:6px}.btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.btn-mini .caret,.btn-small .caret{margin-top:8px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.alert,.alert h4{color:#c09853}.alert h4{margin:0}.alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success h4{color:#468847}.alert-danger,.alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger h4,.alert-error h4{color:#b94a48}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info h4{color:#3a87ad}.alert-block{padding-top:14px;padding-bottom:14px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.nav{margin-bottom:20px;margin-left:0;list-style:none}.nav>li>a{display:block}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li>a>img{max-width:none}.nav>.pull-right{float:right}.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.nav li+.nav-header{margin-top:9px}.nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.nav-list>li>a,.nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.nav-list>li>a{padding:3px 15px}.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#08c}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px}.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.nav-tabs,.nav-pills{*zoom:1}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;line-height:0;content:""}.nav-tabs:after,.nav-pills:after{clear:both}.nav-tabs>li,.nav-pills>li{float:left}.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{margin-bottom:-1px}.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eee #eee #ddd}.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#fff;background-color:#08c}.nav-stacked>li{float:none}.nav-stacked>li>a{margin-right:0}.nav-tabs.nav-stacked{border-bottom:0}.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.nav-pills.nav-stacked>li>a{margin-bottom:3px}.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#08c;border-bottom-color:#08c}.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580}.nav-tabs .dropdown-toggle .caret{margin-top:8px}.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#999;border-color:#999}.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999}.tabbable{*zoom:1}.tabbable:before,.tabbable:after{display:table;line-height:0;content:""}.tabbable:after{clear:both}.tab-content{overflow:auto}.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #ddd}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eee #ddd #eee #eee}.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eee #eee #ddd}.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.nav>.disabled>a{color:#999}.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.navbar-inner{min-height:40px;padding-right:20px;padding-left:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top,#fff,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#fff,#f2f2f2);background-image:-o-linear-gradient(top,#fff,#f2f2f2);background-image:linear-gradient(to bottom,#fff,#f2f2f2);background-repeat:repeat-x;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff2f2f2',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.navbar-inner:before,.navbar-inner:after{display:table;line-height:0;content:""}.navbar-inner:after{clear:both}.navbar .container{width:auto}.nav-collapse.collapse{height:auto;overflow:visible}.navbar .brand{display:block;float:left;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777;text-shadow:0 1px 0 #fff}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none}.navbar-text{margin-bottom:0;line-height:40px;color:#777}.navbar-link{color:#777}.navbar-link:hover,.navbar-link:focus{color:#333}.navbar .divider-vertical{height:40px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #f2f2f2}.navbar .btn,.navbar .btn-group{margin-top:5px}.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0}.navbar-form{margin-bottom:0;*zoom:1}.navbar-form:before,.navbar-form:after{display:table;line-height:0;content:""}.navbar-form:after{clear:both}.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px}.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0}.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px}.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0}.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0}.navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.navbar-static-top{position:static;margin-bottom:0}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px}.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.navbar-fixed-top{top:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar-fixed-bottom{bottom:0}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.navbar .nav.pull-right{float:right;margin-right:0}.navbar .nav>li{float:left}.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777;text-decoration:none;text-shadow:0 1px 0 #fff}.navbar .nav .dropdown-toggle .caret{margin-top:8px}.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{color:#333;text-decoration:none;background-color:transparent}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ededed;*background-color:#e5e5e5;background-image:-moz-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-o-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:linear-gradient(to bottom,#f2f2f2,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffe5e5e5',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#fff;background-color:#e5e5e5;*background-color:#d9d9d9}.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#ccc \9}.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.btn-navbar .icon-bar+.icon-bar{margin-top:3px}.navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#555;background-color:#e5e5e5}.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777;border-bottom-color:#777}.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#fff}.navbar-inverse .brand{color:#999}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#fff}.navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-moz-linear-gradient(top,#151515,#040404);background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000 \9}.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.breadcrumb>li>.divider{padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{margin:20px 0}.pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.pagination ul>li{display:inline}.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5}.pagination ul>.active>a,.pagination ul>.active>span{color:#999;cursor:default}.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999;cursor:default;background-color:transparent}.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.pagination-centered{text-align:center}.pagination-right{text-align:right}.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.pager:before,.pager:after{display:table;line-height:0;content:""}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:default;background-color:#fff}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop,.modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.modal.fade.in{top:10%}.modal-header{padding:9px 15px;border-bottom:1px solid #eee}.modal-header .close{margin-top:2px}.modal-header h3{margin:0;line-height:30px}.modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.modal-form{margin-bottom:0}.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.modal-footer:before,.modal-footer:after{display:table;line-height:0;content:""}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.tooltip{position:absolute;z-index:1030;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.8;filter:alpha(opacity=80)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.popover-title:empty{display:none}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.thumbnails{margin-left:-20px;list-style:none;*zoom:1}.thumbnails:before,.thumbnails:after{display:table;line-height:0;content:""}.thumbnails:after{clear:both}.row-fluid .thumbnails{margin-left:0}.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}a.thumbnail:hover,a.thumbnail:focus{border-color:#08c;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#555}.media,.media-body{overflow:hidden;*overflow:visible;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{margin-left:0;list-style:none}.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#999}.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.label:empty,.badge:empty{display:none}a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.label-important,.badge-important{background-color:#b94a48}.label-important[href],.badge-important[href]{background-color:#953b39}.label-warning,.badge-warning{background-color:#f89406}.label-warning[href],.badge-warning[href]{background-color:#c67605}.label-success,.badge-success{background-color:#468847}.label-success[href],.badge-success[href]{background-color:#356635}.label-info,.badge-info{background-color:#3a87ad}.label-info[href],.badge-info[href]{background-color:#2d6987}.label-inverse,.badge-inverse{background-color:#333}.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a}.btn .label,.btn .badge{position:relative;top:-1px}.btn-mini .label,.btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0)}.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px}.accordion-toggle{cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative;margin-bottom:20px;line-height:1}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.carousel-control.right{right:15px;left:auto}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#333;background:rgba(0,0,0,0.75)}.carousel-caption h4,.carousel-caption p{line-height:20px;color:#fff}.carousel-caption h4{margin:0 0 5px}.carousel-caption p{margin-bottom:0}.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:inherit}.hero-unit li{line-height:30px}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache new file mode 100644 index 00000000000..35687dd18e4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache @@ -0,0 +1,101 @@ +/* Pretty printing styles. Used with prettify.js. */ +/* Vim sunburst theme by David Leibovic */ +pre .str { + color: #65B042; +} +/* string - green */ +pre .kwd { + color: #E28964; +} +/* keyword - dark pink */ +pre .com { + color: #AEAEAE; + font-style: italic; +} +/* comment - gray */ +pre .typ { + color: #89bdff; +} +/* type - light blue */ +pre .lit { + color: #3387CC; +} +/* literal - blue */ +pre .pun { + color: #fff; +} +/* punctuation - white */ +pre .pln { + color: #fff; +} +/* plaintext - white */ +pre .tag { + color: #89bdff; +} +/* html/xml tag - light blue */ +pre .atn { + color: #bdb76b; +} +/* html/xml attribute name - khaki */ +pre .atv { + color: #65B042; +} +/* html/xml attribute value - green */ +pre .dec { + color: #3387CC; +} +/* decimal - blue */ +/* Specify class=linenums on a pre to get line numbering */ +ol.linenums { + margin-top: 0; + margin-bottom: 0; + color: #AEAEAE; +} +/* IE indents via margin-left */ +li.L0, +li.L1, +li.L2, +li.L3, +li.L5, +li.L6, +li.L7, +li.L8 { + list-style-type: none; +} +/* Alternate shading for lines */ +@media print { + pre .str { + color: #060; + } + pre .kwd { + color: #006; + font-weight: bold; + } + pre .com { + color: #600; + font-style: italic; + } + pre .typ { + color: #404; + font-weight: bold; + } + pre .lit { + color: #044; + } + pre .pun { + color: #440; + } + pre .pln { + color: #000; + } + pre .tag { + color: #006; + font-weight: bold; + } + pre .atn { + color: #404; + } + pre .atv { + color: #060; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache new file mode 100644 index 00000000000..c07ed7ca1e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -0,0 +1,555 @@ + + + + + {{{appName}}} + + + + + +{{>js_jquery}} + +{{>js_prettify}} +{{>js_bootstrap}} + + + + + + + + + + +
    +
    +
    + +
    +
    +
    +
    +

    {{{appName}}}

    +
    +
    +
    + +
    + + {{#apiInfo}} + + {{#apis}} + {{#operations}} +
    +

    {{baseName}}

    + {{#operation}} + + + + + + + +
    + +
    +
    +

    {{nickname}}

    +
    +
    + +
    +
    + +

    +

    {{notes}}

    +

    +
    + +
    {{path}}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    +
    +
    +
    +
    + +
    +
    
    +{{>sample_java}}
    +                                                  
    +
    + + +
    +
    
    +{{>sample_android}}
    +                                                  
    +
    + + + + +
    +
    
    +{{>sample_objc}}
    +                                                    
    +
    +
    +
    
    +{{>sample_js}}
    +                                                    
    +
    + + + +
    +
    
    +{{>sample_csharp}}
    +                                                    
    +
    + + +
    +
    
    +{{>sample_php}}
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + {{#hasPathParams}} +
    Path parameters
    + + + + + + + {{#pathParams}} + {{>param}} + {{/pathParams}} +
    NameDescription
    + {{/hasPathParams}} + + {{#hasHeaderParams}} +
    Header parameters
    + + + + + + + {{#headerParams}} + {{>param}} + {{/headerParams}} + +
    NameDescription
    + {{/hasHeaderParams}} + + + {{#hasBodyParam}} +
    Body parameters
    + + + + + + + {{#bodyParams}} + {{>paramB}} + {{/bodyParams}} + +
    NameDescription
    + {{/hasBodyParam}} + + {{#hasQueryParams}} +
    Query parameters
    + + + + + + + {{#queryParams}} + {{>param}} + {{/queryParams}} +
    NameDescription
    + {{/hasQueryParams}} + +

    Responses

    + {{#responses}} + +

    Status: {{code}} - {{message}}

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + {{#examples}} +
    +
    {{example}}
    +
    + {{/examples}} + + +
    + + + + {{/responses}} + + + + + + +
    + +
    + +
    + + {{/operation}} +
    + + {{/operations}} + {{/apis}} + + {{/apiInfo}} + + + + +
    + + + + + + + +
    +
    + Generated {{generatedDate}} +
    +
    +
    +
    +
    + + + + + + +{{>js_jsonschemaview}} +{{>js_jsonref}} +{{>js_webfontloader}} + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache new file mode 100644 index 00000000000..66770d8b78e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache @@ -0,0 +1,8 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache new file mode 100644 index 00000000000..7e1f8503efe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache @@ -0,0 +1,6 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache new file mode 100644 index 00000000000..406ba0003fc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache @@ -0,0 +1,3 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache new file mode 100644 index 00000000000..d0893c18cd2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache @@ -0,0 +1,313 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache new file mode 100644 index 00000000000..74e8a7b3373 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache @@ -0,0 +1,32 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache new file mode 100644 index 00000000000..5c0716cd1f2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache @@ -0,0 +1,19 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache new file mode 100644 index 00000000000..69cf16352ca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache @@ -0,0 +1,26 @@ +{{paramName}}{{^required}}{{/required}}{{#required}}*{{/required}} + + + + +
    + + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache new file mode 100644 index 00000000000..03aa9ef4d43 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache @@ -0,0 +1,35 @@ +{{paramName}} {{^required}}{{/required}}{{#required}}*{{/required}} + + + + +
    + + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache new file mode 100644 index 00000000000..cb23590bf53 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache @@ -0,0 +1,18 @@ +import {{{package}}}.{{{classname}}}; + +public class {{{classname}}}Example { + + public static void main(String[] args) { + {{{classname}}} apiInstance = new {{{classname}}}(); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + e.printStackTrace(); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache new file mode 100644 index 00000000000..fd7a75d0da2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache @@ -0,0 +1,51 @@ +using System; +using System.Diagnostics; +using {{packageName}}.Api; +using {{packageName}}.Client; +{{#modelPackage}} +using {{{.}}}; +{{/modelPackage}} + +namespace Example +{ + public class {{operationId}}Example + { + public void main() + { + {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + {{/hasAuthMethods}} + + var apiInstance = new {{classname}}(); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (Exception e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + } + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache new file mode 100644 index 00000000000..160916ed81f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache @@ -0,0 +1,41 @@ +import {{{invokerPackage}}}.*; +import {{{invokerPackage}}}.auth.*; +import {{{invokerPackage}}}.model.*; +import {{{package}}}.{{{classname}}}; + +import java.io.File; +import java.util.*; + +public class {{{classname}}}Example { + + public static void main(String[] args) { + {{#hasAuthMethods}}ApiClient defaultClient = Configuration.getDefaultApiClient(); + {{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + e.printStackTrace(); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache new file mode 100644 index 00000000000..8c77656a1a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache @@ -0,0 +1,43 @@ +var {{{moduleName}}} = require('{{{projectName}}}'); +{{#hasAuthMethods}} +var defaultClient = {{{moduleName}}}.ApiClient.instance; +{{#authMethods}}{{#isBasic}} +// Configure HTTP basic authorization: {{{name}}} +var {{{name}}} = defaultClient.authentications['{{{name}}}']; +{{{name}}}.username = 'YOUR USERNAME' +{{{name}}}.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: {{{name}}} +var {{{name}}} = defaultClient.authentications['{{{name}}}']; +{{{name}}}.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//{{{name}}}.apiKeyPrefix['{{{keyParamName}}}'] = "Token"{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: {{{name}}} +var {{{name}}} = defaultClient.authentications['{{{name}}}']; +{{{name}}}.accessToken = "YOUR ACCESS TOKEN"{{/isOAuth}} +{{/authMethods}} +{{/hasAuthMethods}} + +var api = new {{{moduleName}}}.{{{classname}}}(){{#hasParams}} +{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} +{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} +var opts = { {{#allParams}}{{^required}} + '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}{{/required}}{{/allParams}} +};{{/hasOptionalParams}}{{/hasParams}} +{{#usePromises}} +api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { + {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} +}, function(error) { + console.error(error); +}); + +{{/usePromises}}{{^usePromises}} +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} + } +}; +api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}callback); +{{/usePromises}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache new file mode 100644 index 00000000000..88aa2b08b74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache @@ -0,0 +1,34 @@ +{{#hasAuthMethods}} +{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) +[apiConfig setUsername:@"YOUR_USERNAME"]; +[apiConfig setPassword:@"YOUR_PASSWORD"]; +{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: (authentication scheme: {{{name}}}) +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; +{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +{{classname}} *apiInstance = [[{{classname}} alloc] init]; + +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#returnType}} + if (output) { + NSLog(@"%@", output); + } +{{/returnType}} + if (error) { + NSLog(@"Error: %@", error); + } + }]; diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache new file mode 100644 index 00000000000..bb589426f81 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache @@ -0,0 +1,24 @@ +setUsername('YOUR_USERNAME'); +{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: {{{name}}} +{{{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}} +// Configure OAuth2 access token for authorization: {{{name}}} +{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +$api_instance = new {{invokerPackage}}\Api\{{classname}}(); +{{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} +{{/allParams}} + +try { + {{#returnType}}$result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + print_r($result);{{/returnType}} +} catch (Exception $e) { + echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache new file mode 100644 index 00000000000..6b515e10980 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache @@ -0,0 +1,415 @@ +/* ------------------------------------------------------------------------------------------ + * Content + * ------------------------------------------------------------------------------------------ */ +body { + min-width: 980px; +} + +body, p, a, div, th, td { + font-family: "Source Sans Pro", sans-serif; + font-weight: 400; + font-size: 16px; + text-shadow: none !important; +} + +td.code { + font-size: 14px; + font-family: "Source Code Pro", monospace; + font-style: normal; + font-weight: 400; +} + +#content { + padding-top: 16px; + z-Index: -1; + margin-left: 270px; +} + +p { + color: #808080; +} + +h1 { + font-family: "Source Sans Pro Semibold", sans-serif; + font-weight: normal; + font-size: 44px; + line-height: 50px; + margin: 0 0 10px 0; + padding: 0; +} + +h2 { + font-family: "Source Sans Pro", sans-serif; + font-weight: normal; + font-size: 24px; + line-height: 40px; + margin: 0 0 20px 0; + padding: 0; +} + +section { + border-top: 1px solid #ebebeb; + padding: 30px 0; +} + +section h1 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + font-size: 32px; + line-height: 40px; + padding-bottom: 14px; + margin: 0 0 20px 0; + padding: 0; +} + +article { + padding: 14px 0 30px 0; +} + +article h1 { + font-family: "Source Sans Pro Bold", sans-serif; + font-weight: 600; + font-size: 24px; + line-height: 26px; +} + +article h2 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 18px; + line-height: 24px; + margin: 0 0 10px 0; +} + +article h3 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 16px; + line-height: 18px; + margin: 0 0 10px 0; +} + +article h4 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 14px; + line-height: 16px; + margin: 0 0 8px 0; +} + +table { + border-collapse: collapse; + width: 100%; + margin: 0 0 20px 0; +} + +th { + background-color: #f5f5f5; + text-align: left; + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + padding: 4px 8px; + border: #e0e0e0 1px solid; +} + +td { + vertical-align: top; + padding: 2px 8px; + border: #e0e0e0 1px solid; +} + +#generator .content { + color: #b0b0b0; + border-top: 1px solid #ebebeb; + padding: 10px 0; +} + +.label-optional { + float: right; +} + +.open-left { + right: 0; + left: auto; +} + +/* ------------------------------------------------------------------------------------------ + * apidoc - intro + * ------------------------------------------------------------------------------------------ */ + +#apidoc .apidoc { + border-top: 1px solid #ebebeb; + padding: 30px 0; +} + +#apidoc h1 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + font-size: 32px; + line-height: 40px; + padding-bottom: 14px; + margin: 0 0 20px 0; + padding: 0; +} + +#apidoc h2 { + font-family: "Source Sans Pro Bold", sans-serif; + font-weight: 600; + font-size: 22px; + line-height: 26px; + padding-top: 14px; +} + +/* ------------------------------------------------------------------------------------------ + * pre / code + * ------------------------------------------------------------------------------------------ */ +pre { + background-color: #292b36; + color: #ffffff; + padding: 10px; + border-radius: 6px; + position: relative; + margin: 10px 0 20px 0; +} + +code.language-text { + word-wrap: break-word; +} + +pre.language-json { + overflow: auto; +} + +pre.language-html { + margin: 40px 0 20px 0; +} + +pre.language-html:before { + content: attr(data-type); + position: absolute; + top: -30px; + left: 0; + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 15px; + display: inline-block; + padding: 2px 5px; + border-radius: 6px; + text-transform: uppercase; + background-color: #3387CC; + color: #ffffff; +} + +pre.language-html[data-type="get"]:before { + background-color: green; +} + +pre.language-html[data-type="put"]:before { + background-color: #e5c500; +} + +pre.language-html[data-type="post"]:before { + background-color: #4070ec; +} + +pre.language-html[data-type="delete"]:before { + background-color: #ed0039; +} + +pre.language-api .str { + color: #ffffff; +} + +pre.language-api .pln, +pre.language-api .pun { + color: #65B042; +} + +pre code { + display: block; + font-size: 14px; + font-family: "Source Code Pro", monospace; + font-style: normal; + font-weight: 400; +} + +pre code.sample-request-response-json { + white-space: pre-wrap; + max-height: 500px; + overflow: auto; +} + +/* ------------------------------------------------------------------------------------------ + * Sidenav + * ------------------------------------------------------------------------------------------ */ +.sidenav { + width: 228px; + margin: 0; + padding: 20px; + position: fixed; + top: 0; + left: 0; + bottom: 0; + overflow-x: hidden; + overflow-y: auto; + background-color: #f5f5f5; + z-index: 10; +} + +.sidenav > li > a { + display: block; + width: 192px; + margin: 0; + padding: 2px 11px; + border: 0; + border-left: transparent 4px solid; + border-right: transparent 4px solid; + font-family: "Source Sans Pro", sans-serif; + font-weight: 400; + font-size: 14px; +} + +.sidenav > li.nav-header > a { + padding: 5px 15px; + border: 1px solid #e5e5e5; + width: 190px; + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + font-size: 16px; + background-color: #4c8eca; + color: #fff; +} + +.sidenav > li.nav-header.active > a { + background-color: #4c8eca; + color: #fff; +} + + +00427D + +.sidenav > .active > a { + position: relative; + z-index: 2; +} + +.sidenav > li > a:hover { + background-color: #ffffff; +} + +.sidenav > li.has-modifications a { + border-right: #60d060 4px solid; +} + +.sidenav > li.is-new a { + border-left: #e5e5e5 4px solid; +} + + + +/* ------------------------------------------------------------------------------------------ + * Tabs + * ------------------------------------------------------------------------------------------ */ +ul.nav-tabs { + margin: 0; +} + +/* ------------------------------------------------------------------------------------------ + * Print + * ------------------------------------------------------------------------------------------ */ + +@media print { + + #sidenav, + #version, + #versions, + section .version, + section .versions { + display: none; + } + + #content { + margin-left: 0; + } + + a { + text-decoration: none; + color: inherit; + } + + a:after { + content: " [" attr(href) "] "; + } + + p { + color: #000000 + } + + pre { + background-color: #ffffff; + color: #000000; + padding: 10px; + border: #808080 1px solid; + border-radius: 6px; + position: relative; + margin: 10px 0 20px 0; + } + +} /* /@media print */ + + +.doc-chapter +{ +display:none; +background-color: #eee; +border-radius: 1px; +padding: 10px; +margin-bottom: 20px; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/*! + * json-schema-view-js + * https://github.com/mohsen1/json-schema-view-js#readme + * Version: 0.4.1 - 2015-11-12T17:19:27.615Z + * License: MIT + */.json-schema-view .toggle-handle:after,.json-schema-view.json-schema-view-dark .toggle-handle:after,json-schema-view .toggle-handle:after,json-schema-view[json-schema-view-dark] .toggle-handle:after{content:"\25BC"}.json-schema-view .title,.json-schema-view.json-schema-view-dark .title,json-schema-view .title,json-schema-view[json-schema-view-dark] .title{font-weight:700;cursor:pointer}.json-schema-view,json-schema-view{font-family:monospace;font-size:0;display:table-cell}.json-schema-view>*,json-schema-view>*{font-size:14px}.json-schema-view .toggle-handle,json-schema-view .toggle-handle{cursor:pointer;margin:auto .3em;font-size:10px;display:inline-block;transform-origin:50% 40%;transition:transform 150ms ease-in}.json-schema-view .toggle-handle,.json-schema-view .toggle-handle:hover,json-schema-view .toggle-handle,json-schema-view .toggle-handle:hover{text-decoration:none;color:#333}.json-schema-view .description,json-schema-view .description{color:gray;font-style:italic} + .pattern { + color: blue; + } + .default { + color: black; + } + .required { + color:black; + } + .json-schema-view .title,.json-schema-view .title:hover,json-schema-view .title,json-schema-view .title:hover{text-decoration:none;color:#333}.json-schema-view .brace,.json-schema-view .bracket,.json-schema-view .title,json-schema-view .brace,json-schema-view .bracket,json-schema-view .title{color:#333}.json-schema-view .property,json-schema-view .property{font-size:0;display:table-row}.json-schema-view .property>*,json-schema-view .property>*{font-size:14px;padding:.2em}.json-schema-view .name,json-schema-view .name{color:#00f;display:table-cell;vertical-align:top}.json-schema-view .type,json-schema-view .type{color:green}.json-schema-view .type-any,json-schema-view .type-any{color:#33f}.json-schema-view .required,json-schema-view .required{color:red}.json-schema-view .inner,json-schema-view .inner{padding-left:18px}.json-schema-view.collapsed .description,.json-schema-view.collapsed .property,json-schema-view.collapsed .description,json-schema-view.collapsed .property{display:none}.json-schema-view.collapsed .closeing.brace,json-schema-view.collapsed .closeing.brace{display:inline-block}.json-schema-view.collapsed .toggle-handle,json-schema-view.collapsed .toggle-handle{transform:rotate(-90deg)}.json-schema-view.json-schema-view-dark,json-schema-view[json-schema-view-dark]{font-family:monospace;font-size:0;display:table-cell}.json-schema-view.json-schema-view-dark>*,json-schema-view[json-schema-view-dark]>*{font-size:14px}.json-schema-view.json-schema-view-dark .toggle-handle,json-schema-view[json-schema-view-dark] .toggle-handle{cursor:pointer;margin:auto .3em;font-size:10px;display:inline-block;transform-origin:50% 40%;transition:transform 150ms ease-in}.json-schema-view.json-schema-view-dark .toggle-handle,.json-schema-view.json-schema-view-dark .toggle-handle:hover,json-schema-view[json-schema-view-dark] .toggle-handle,json-schema-view[json-schema-view-dark] .toggle-handle:hover{text-decoration:none;color:#eee}.json-schema-view.json-schema-view-dark .description,json-schema-view[json-schema-view-dark] .description{color:gray;font-style:italic}.json-schema-view.json-schema-view-dark .title,.json-schema-view.json-schema-view-dark .title:hover,json-schema-view[json-schema-view-dark] .title,json-schema-view[json-schema-view-dark] .title:hover{text-decoration:none;color:#eee}.json-schema-view.json-schema-view-dark .brace,.json-schema-view.json-schema-view-dark .bracket,.json-schema-view.json-schema-view-dark .title,json-schema-view[json-schema-view-dark] .brace,json-schema-view[json-schema-view-dark] .bracket,json-schema-view[json-schema-view-dark] .title{color:#eee}.json-schema-view.json-schema-view-dark .property,json-schema-view[json-schema-view-dark] .property{font-size:0;display:table-row}.json-schema-view.json-schema-view-dark .property>*,json-schema-view[json-schema-view-dark] .property>*{font-size:14px;padding:.2em}.json-schema-view.json-schema-view-dark .name,json-schema-view[json-schema-view-dark] .name{color:#add8e6;display:table-cell;vertical-align:top}.json-schema-view.json-schema-view-dark .type,json-schema-view[json-schema-view-dark] .type{color:#90ee90}.json-schema-view.json-schema-view-dark .type-any,json-schema-view[json-schema-view-dark] .type-any{color:#d4ebf2}.json-schema-view.json-schema-view-dark .required,json-schema-view[json-schema-view-dark] .required{color:#fe0000}.json-schema-view.json-schema-view-dark .inner,json-schema-view[json-schema-view-dark] .inner{padding-left:18px}.json-schema-view.json-schema-view-dark.collapsed .description,.json-schema-view.json-schema-view-dark.collapsed .property,json-schema-view[json-schema-view-dark].collapsed .description,json-schema-view[json-schema-view-dark].collapsed .property{display:none}.json-schema-view.json-schema-view-dark.collapsed .closeing.brace,json-schema-view[json-schema-view-dark].collapsed .closeing.brace{display:inline-block}.json-schema-view.json-schema-view-dark.collapsed .toggle-handle,json-schema-view[json-schema-view-dark].collapsed .toggle-handle{transform:rotate(-90deg)} diff --git a/modules/swagger-codegen/src/main/resources/lumen/api.mustache b/modules/swagger-codegen/src/main/resources/lumen/api.mustache index fb735e2fb8e..277bbcd3df3 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/api.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/api.mustache @@ -43,20 +43,30 @@ use Illuminate\Support\Facades\Request; } {{/minLength}} {{#maximum}} - if (${{paramName}}] > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if (${{paramName}}] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if (${{paramName}}] < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if (${{paramName}}] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", ${{paramName}}])) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.'); + if (!preg_match("{{{pattern}}}", ${{paramName}}])) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} + {{#maxItems}} + if (count(${{paramName}}]) > {{maxItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); + } + {{/maxItems}} + {{#minItems}} + if (count(${{paramName}}]) < {{minItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} {{/pathParams}} @@ -81,20 +91,30 @@ use Illuminate\Support\Facades\Request; } {{/minLength}} {{#maximum}} - if ($input['{{paramName}}'] > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if ($input['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if ($input['{{paramName}}'] < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if ($input['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", $input['{{paramName}}'])) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.'); + if (!preg_match("{{{pattern}}}", $input['{{paramName}}'])) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} + {{#maxItems}} + if (count($input['{{paramName}}']) > {{maxItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); + } + {{/maxItems}} + {{#minItems}} + if (count($input['{{paramName}}']) < {{minItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} ${{paramName}} = $input['{{paramName}}']; diff --git a/modules/swagger-codegen/src/main/resources/lumen/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/lumen/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lumen/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/lumen/routes.mustache b/modules/swagger-codegen/src/main/resources/lumen/routes.mustache index c5f3bdf858a..4b9631fd9a5 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/routes.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/routes.mustache @@ -19,7 +19,7 @@ $app->get('/', function () use ($app) { * Notes: {{notes}} {{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} */ -$app->{{httpMethod}}('{{path}}', '{{classname}}@{{operationId}}'); +$app->{{httpMethod}}('{{basePathWithoutHost}}{{path}}', '{{classname}}@{{operationId}}'); {{/operation}} {{/operations}} {{/apis}} diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache index 5b63a52feb2..c4a06b60070 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache @@ -7,7 +7,7 @@ Library Properties {{packageName}}.{{packageContext}} - {{packageTitle}} + {{packageName}} {{^supportsUWP}} v4.5 {{/supportsUWP}} diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache index 5a7a89aa528..0c6a219e7bb 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache @@ -1,4 +1,10 @@ /// /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} /// - public enum {{>innerApiEnumName}} { {{#allowableValues}}{{#values}}{{&.}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}} }; \ No newline at end of file + public enum {{>innerApiEnumName}} + { + {{#allowableValues}} +{{#values}} {{&.}}{{^-last}}, {{/-last}} +{{/values}} + {{/allowableValues}} + }; diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnumName.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnumName.mustache index f54069fb50c..f2b90daa144 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnumName.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnumName.mustache @@ -1 +1 @@ -{{#datatypeWithEnum}}{{operationId}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} \ No newline at end of file +{{#datatypeWithEnum}}{{operationId}}{{^isContainer}}{{.}}{{/isContainer}}{{#isContainer}}{{{items.datatypeWithEnum}}}{{/isContainer}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index be5eba32ee0..74ffd6f78c1 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -128,7 +128,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index db56c1b4b77..1b917176eaa 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -8,7 +8,9 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: {{appVersion}} - Package version: {{artifactVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -55,7 +57,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. ## Getting Started @@ -84,10 +86,10 @@ Please follow the [installation procedure](#installation--usage) and then run th {{classname}} *apiInstance = [[{{classname}} alloc] init]; -{{#summary}} // {{{.}}} +{{#summary}}// {{{.}}} {{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) { + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { {{#returnType}} if (output) { NSLog(@"%@", output); diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache index 812ed061c04..4d303fc344f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache @@ -223,7 +223,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}UnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 2a4a548458e..5ca9303e5a8 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -28,6 +28,9 @@ return [super initWithDictionary:dict error:err]; } Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); + if(!class) { + class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:[discriminatedClassName capitalizedString]]); + } if([self class ] == class) { return [super initWithDictionary:dict error:err]; } diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 500d816b178..135349fdd82 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -17,9 +17,9 @@ use constant VERSION => '{{moduleVersion}}'; # class/static variables our $http_timeout = 180; -our $http_user_agent = 'Perl-Swagger'; +our $http_user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{moduleVersion}}}/perl{{/httpUserAgent}}'; -# authenticaiton setting +# authentication setting our $api_key = {}; our $api_key_prefix = {}; our $api_key_in = {}; diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index d47d482742d..c732448cecf 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -251,6 +251,8 @@ use warnings; {{/model}}{{/models}} # for displaying the API response data use Data::Dumper; +use {{{moduleName}}}::Configuration; +use {{moduleName}}::{{classname}}; {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} # Configure HTTP basic authorization: {{{name}}} ${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; @@ -264,7 +266,7 @@ ${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth} {{/hasAuthMethods}} my $api_instance = {{moduleName}}::{{classname}}->new(); -{{#allParams}}my ${{paramName}} = {{#isListContainer}}({{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}){{/isListContainer}}; # {{{dataType}}} | {{{description}}} +{{#allParams}}my ${{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; # {{{dataType}}} | {{{description}}} {{/allParams}} eval { @@ -290,7 +292,7 @@ Class | Method | HTTP request | Description {{#models}}{{#model}} - [{{moduleName}}::Object::{{classname}}]({{modelDocPath}}{{classname}}.md) {{/model}}{{/models}} -# DOCUMENTATION FOR AUTHORIATION +# DOCUMENTATION FOR AUTHORIZATION {{^authMethods}} All endpoints do not require authorization. {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}## {{{name}}} diff --git a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache index 585a67c1ac1..acc6b4a003f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache @@ -25,6 +25,8 @@ Method | HTTP request | Description ### Example ```perl use Data::Dumper; +use {{{moduleName}}}::Configuration; +use {{moduleName}}::{{classname}}; {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} # Configure HTTP basic authorization: {{{name}}} ${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; @@ -38,7 +40,7 @@ ${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth} {{/hasAuthMethods}} my $api_instance = {{moduleName}}::{{classname}}->new(); -{{#allParams}}my ${{paramName}} = {{#isListContainer}}({{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}){{/isListContainer}}; # {{{dataType}}} | {{{description}}} +{{#allParams}}my ${{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; # {{{dataType}}} | {{{description}}} {{/allParams}} eval { diff --git a/modules/swagger-codegen/src/main/resources/php/.php_cs b/modules/swagger-codegen/src/main/resources/php/.php_cs new file mode 100644 index 00000000000..6b8e23c818a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/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/modules/swagger-codegen/src/main/resources/php/.travis.yml b/modules/swagger-codegen/src/main/resources/php/.travis.yml index 3c97d942552..d77f3825f6f 100644 --- a/modules/swagger-codegen/src/main/resources/php/.travis.yml +++ b/modules/swagger-codegen/src/main/resources/php/.travis.yml @@ -7,4 +7,4 @@ php: - 7.0 - hhvm before_install: "composer install" -script: "phpunit lib/Tests" +script: "vendor/bin/phpunit" diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 5b21f922c6b..effdbedb7f8 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -7,7 +7,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -26,12 +26,11 @@ namespace {{invokerPackage}}; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClient { - public static $PATCH = "PATCH"; public static $POST = "POST"; public static $GET = "GET"; @@ -61,7 +60,7 @@ class ApiClient */ public function __construct(\{{invokerPackage}}\Configuration $config = null) { - if ($config == null) { + if ($config === null) { $config = Configuration::getDefaultConfiguration(); } @@ -130,8 +129,7 @@ class ApiClient */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) { - - $headers = array(); + $headers = []; // construct the http header $headerParams = array_merge( @@ -144,9 +142,9 @@ class ApiClient } // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model $postData = json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($postData)); } @@ -154,7 +152,7 @@ class ApiClient $curl = curl_init(); // set timeout, if needed - if ($this->config->getCurlTimeout() != 0) { + if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just true @@ -163,7 +161,7 @@ class ApiClient curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // disable SSL verification, if needed - if ($this->config->getSSLVerification() == false) { + if ($this->config->getSSLVerification() === false) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } @@ -172,24 +170,24 @@ class ApiClient $url = ($url . '?' . http_build_query($queryParams)); } - if ($method == self::$POST) { + if ($method === self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$HEAD) { + } elseif ($method === self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method == self::$OPTIONS) { + } elseif ($method === self::$OPTIONS) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$PATCH) { + } elseif ($method === self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$PUT) { + } elseif ($method === self::$PUT) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$DELETE) { + } elseif ($method === self::$DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method != self::$GET) { + } elseif ($method !== self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -223,12 +221,24 @@ class ApiClient } // Handle the response - if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + if ($response_info['http_code'] === 0) { + $curl_error_message = curl_error($curl); + + // curl_exec can sometimes fail but still return a blank message from curl_error(). + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; + } else { + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; + } + + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); + throw $exception; } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file - if ($responseType == '\SplFileObject' || $responseType == 'string') { - return array($http_body, $response_info['http_code'], $http_header); + if ($responseType === '\SplFileObject' || $responseType === 'string') { + return [$http_body, $response_info['http_code'], $http_header]; } $data = json_decode($http_body); @@ -248,7 +258,7 @@ class ApiClient $data ); } - return array($data, $response_info['http_code'], $http_header); + return [$data, $response_info['http_code'], $http_header]; } /** @@ -297,7 +307,7 @@ class ApiClient protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = array(); + $headers = []; $key = ''; foreach (explode("\n", $raw_headers) as $h) { @@ -307,14 +317,14 @@ class ApiClient if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); + $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); } else { - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); + $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); } $key = $h[0]; } else { - if (substr($h[0], 0, 1) == "\t") { + if (substr($h[0], 0, 1) === "\t") { $headers[$key] .= "\r\n\t".trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 2cffdea5ccf..f99a793fbc6 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -27,7 +27,7 @@ use \Exception; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiException extends Exception diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 4f99eaac4c3..7208e4c7784 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -7,7 +7,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -26,18 +26,17 @@ namespace {{invokerPackage}}; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializer { - /** * Serialize data * * @param mixed $data the data to serialize * - * @return string serialized form of $data + * @return string|object serialized form of $data */ public static function sanitizeForSerialization($data) { @@ -51,7 +50,7 @@ class ObjectSerializer } return $data; } elseif (is_object($data)) { - $values = array(); + $values = []; foreach (array_keys($data::swaggerTypes()) as $property) { $getter = $data::getters()[$property]; if ($data->$getter() !== null) { @@ -100,7 +99,7 @@ class ObjectSerializer * If it's a string, pass through unchanged. It will be url-encoded * later. * - * @param object $object an object to be serialized to a string + * @param string[]|string|\DateTime $object an object to be serialized to a string * * @return string the serialized object */ @@ -132,7 +131,7 @@ class ObjectSerializer * the http body (form parameter). If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the form parameter + * @param string|\SplFileObject $value the value of the form parameter * * @return string the form string */ @@ -150,7 +149,7 @@ class ObjectSerializer * the parameter. If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the parameter + * @param string|\DateTime $value the value of the parameter * * @return string the header string */ @@ -166,9 +165,10 @@ class ObjectSerializer /** * Serialize an array to a string. * - * @param array $collection collection to serialize to a string - * @param string $collectionFormat the format use for serialization (csv, + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array * * @return string */ @@ -199,12 +199,12 @@ class ObjectSerializer /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @param string $httpHeaders HTTP headers - * @param string $discriminator discriminator if polymorphism is used + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used * - * @return object an instance of $class + * @return object|array|null an single or an array of $class instances */ public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { @@ -212,7 +212,7 @@ class ObjectSerializer return null; } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); - $deserialized = array(); + $deserialized = []; if (strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; @@ -221,9 +221,9 @@ class ObjectSerializer } } return $deserialized; - } elseif (strcasecmp(substr($class, -2), '[]') == 0) { + } elseif (strcasecmp(substr($class, -2), '[]') === 0) { $subClass = substr($class, 0, -2); - $values = array(); + $values = []; foreach ($data as $key => $value) { $values[] = self::deserialize($value, $subClass, null, $discriminator); } @@ -243,7 +243,7 @@ class ObjectSerializer } else { return null; } - } elseif (in_array($class, array({{&primitives}}))) { + } elseif (in_array($class, [{{&primitives}}], true)) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { @@ -256,7 +256,6 @@ class ObjectSerializer } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); } diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index 4186ed0ea99..ab0da1711f2 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -9,7 +9,9 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git {{#artifactVersion}} - Package version: {{artifactVersion}} {{/artifactVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -54,7 +56,7 @@ To run the unit tests: ``` composer install -./vendor/bin/phpunit lib/Tests +./vendor/bin/phpunit ``` ## Getting Started diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index dfc079874e9..26583a6f3d1 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -19,9 +19,9 @@ namespace {{apiPackage}}; -use \{{invokerPackage}}\Configuration; use \{{invokerPackage}}\ApiClient; use \{{invokerPackage}}\ApiException; +use \{{invokerPackage}}\Configuration; use \{{invokerPackage}}\ObjectSerializer; /** @@ -30,12 +30,11 @@ use \{{invokerPackage}}\ObjectSerializer; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ {{#operations}}class {{classname}} { - /** * API Client * @@ -50,7 +49,7 @@ use \{{invokerPackage}}\ObjectSerializer; */ public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) { - if ($apiClient == null) { + if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('{{basePath}}'); } @@ -80,8 +79,8 @@ use \{{invokerPackage}}\ObjectSerializer; $this->apiClient = $apiClient; return $this; } - {{#operation}} + /** * Operation {{{operationId}}} * @@ -94,8 +93,8 @@ use \{{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} - * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -114,9 +113,9 @@ use \{{invokerPackage}}\ObjectSerializer; {{/description}} {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} - * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) +{{/allParams}} * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -129,44 +128,54 @@ use \{{invokerPackage}}\ObjectSerializer; {{/required}} {{#hasValidation}} {{#maxLength}} - if (strlen(${{paramName}}) > {{maxLength}}) { + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(strlen(${{paramName}}) > {{maxLength}})) { throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); } {{/maxLength}} {{#minLength}} - if (strlen(${{paramName}}) < {{minLength}}) { + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(strlen(${{paramName}}) < {{minLength}})) { throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); } {{/minLength}} {{#maximum}} - if (${{paramName}} > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if (${{paramName}} < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", ${{paramName}})) { - throw new \InvalidArgumentException('invalid value for "{{paramName}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.'); + if ({{^required}}!is_null(${{paramName}}) && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { + throw new \InvalidArgumentException("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}})) { + throw new \InvalidArgumentException('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}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} {{/allParams}} // parse inputs $resourcePath = "{{path}}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{{mediaType}}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]); {{#queryParams}} // query params @@ -277,10 +286,10 @@ use \{{invokerPackage}}\ObjectSerializer; ); {{#returnType}} - return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader]; {{/returnType}} {{^returnType}} - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; {{/returnType}} } catch (ApiException $e) { switch ($e->getCode()) { @@ -297,7 +306,6 @@ use \{{invokerPackage}}\ObjectSerializer; throw $e; } } - {{/operation}} } -{{/operations}} +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index 4b961b3236b..99ad7065c9b 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -30,7 +30,7 @@ use \{{invokerPackage}}\ObjectSerializer; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ {{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 477e0819324..620e74b2c03 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -11,7 +11,7 @@ "api" ], "homepage": "http://swagger.io", - "license": "Apache v2", + "license": "Apache-2.0", "authors": [ { "name": "Swagger and contributors", @@ -27,7 +27,8 @@ "require-dev": { "phpunit/phpunit": "~4.8", "satooshi/php-coveralls": "~1.0", - "squizlabs/php_codesniffer": "~2.6" + "squizlabs/php_codesniffer": "~2.6", + "friendsofphp/php-cs-fixer": "~1.12" }, "autoload": { "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 7e3883cf9c4..bae256b3bd3 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -26,12 +26,11 @@ namespace {{invokerPackage}}; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Configuration { - private static $defaultConfiguration = null; /** @@ -39,14 +38,14 @@ class Configuration * * @var string[] */ - protected $apiKeys = array(); + protected $apiKeys = []; /** * Associate array to store API prefix (e.g. Bearer) * * @var string[] */ - protected $apiKeyPrefixes = array(); + protected $apiKeyPrefixes = []; /** * Access token for OAuth @@ -70,11 +69,11 @@ class Configuration protected $password = ''; /** - * The default instance of ApiClient + * The default header(s) * - * @var \{{invokerPackage}}\ApiClient + * @var array */ - protected $defaultHeaders = array(); + protected $defaultHeaders = []; /** * The host @@ -262,7 +261,7 @@ class Configuration * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * - * @return ApiClient + * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) { @@ -324,7 +323,7 @@ class Configuration * * @param string $userAgent the user agent of the api client * - * @return ApiClient + * @return Configuration */ public function setUserAgent($userAgent) { @@ -351,7 +350,7 @@ class Configuration * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * - * @return ApiClient + * @return Configuration */ public function setCurlTimeout($seconds) { @@ -472,7 +471,7 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { + if (self::$defaultConfiguration === null) { self::$defaultConfiguration = new Configuration(); } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index d80f5d0f485..efecdf2e596 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -9,7 +9,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -31,13 +31,11 @@ use \ArrayAccess; {{#description}} // @description {{description}} {{/description}} -/** +/** * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ {{#isEnum}}{{>model_enum}}{{/isEnum}}{{^isEnum}}{{>model_generic}}{{/isEnum}} - -{{/model}} -{{/models}} +{{/model}}{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache index ffb268c6cb9..c9250081b82 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache @@ -15,4 +15,4 @@ class {{classname}} { ]; } {{/isEnum}}{{/vars}} -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 6e4a3e03f99..1e221b78377 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -10,10 +10,10 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); + ]; public static function swaggerTypes() { @@ -24,45 +24,47 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); + ]; - public static function attributeMap() - { - return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); + ]; - public static function setters() - { - return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); + ]; + + public static function attributeMap() + { + return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; + } + + public static function setters() + { + return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; + } public static function getters() { return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } - {{#vars}}{{#isEnum}}{{#allowableValues}}{{#enumVars}}const {{datatypeWithEnum}}_{{{name}}} = {{{value}}}; + {{#vars}}{{#isEnum}}{{#allowableValues}}{{#enumVars}}const {{enumName}}_{{{name}}} = {{{value}}}; {{/enumVars}}{{/allowableValues}}{{/isEnum}}{{/vars}} {{#vars}}{{#isEnum}} @@ -73,7 +75,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple public function {{getter}}AllowableValues() { return [ - {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} + {{#allowableValues}}{{#enumVars}}self::{{enumName}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} ]; } @@ -83,11 +85,11 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -113,7 +115,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; {{#vars}} {{#required}} if ($this->container['{{name}}'] === null) { @@ -121,37 +123,57 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/required}} {{#isEnum}} - $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); + {{^isContainer}} + $allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]; if (!in_array($this->container['{{name}}'], $allowed_values)) { $invalid_properties[] = "invalid value for '{{name}}', must be one of #{allowed_values}."; } + + {{/isContainer}} {{/isEnum}} {{#hasValidation}} {{#maxLength}} - if (strlen($this->container['{{name}}']) > {{maxLength}}) { + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(strlen($this->container['{{name}}']) > {{maxLength}})) { $invalid_properties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; } + {{/maxLength}} {{#minLength}} - if (strlen($this->container['{{name}}']) < {{minLength}}) { + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(strlen($this->container['{{name}}']) < {{minLength}})) { $invalid_properties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; } + {{/minLength}} {{#maximum}} - if ($this->container['{{name}}'] > {{maximum}}) { - $invalid_properties[] = "invalid value for '{{name}}', must be smaller than or equal to {{maximum}}."; + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { + $invalid_properties[] = "invalid value for '{{name}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}."; } + {{/maximum}} {{#minimum}} - if ($this->container['{{name}}'] < {{minimum}}) { - $invalid_properties[] = "invalid value for '{{name}}', must be bigger than or equal to {{minimum}}."; + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { + $invalid_properties[] = "invalid value for '{{name}}', must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}."; } + {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { - $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{pattern}}."; + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}!preg_match("{{{pattern}}}", $this->container['{{name}}'])) { + $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{{pattern}}}."; } + {{/pattern}} + {{#maxItems}} + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(count($this->container['{{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->container['{{name}}']) && {{/required}}(count($this->container['{{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; @@ -172,10 +194,12 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/required}} {{#isEnum}} - $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); + {{^isContainer}} + $allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]; if (!in_array($this->container['{{name}}'], $allowed_values)) { return false; } + {{/isContainer}} {{/isEnum}} {{#hasValidation}} {{#maxLength}} @@ -189,20 +213,30 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/minLength}} {{#maximum}} - if ($this->container['{{name}}'] > {{maximum}}) { + if ($this->container['{{name}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { return false; } {{/maximum}} {{#minimum}} - if ($this->container['{{name}}'] < {{minimum}}) { + if ($this->container['{{name}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { return false; } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { + if (!preg_match("{{{pattern}}}", $this->container['{{name}}'])) { return false; } {{/pattern}} + {{#maxItems}} + if (count($this->container['{{name}}']) > {{maxItems}}) { + return false; + } + {{/maxItems}} + {{#minItems}} + if (count($this->container['{{name}}']) < {{minItems}}) { + return false; + } + {{/minItems}} {{/hasValidation}} {{/vars}} return true; @@ -228,35 +262,51 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple { {{#isEnum}} $allowed_values = array({{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); - if (!in_array(${{{name}}}, $allowed_values)) { + {{^isContainer}} + if ({{^required}}!is_null(${{name}}) && {{/required}}(!in_array(${{{name}}}, $allowed_values))) { + throw new \InvalidArgumentException("Invalid value for '{{name}}', must be one of {{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"); + } + {{/isContainer}} + {{#isContainer}} + if ({{^required}}!is_null(${{name}}) && {{/required}}(array_diff(${{{name}}}, $allowed_values))) { throw new \InvalidArgumentException("Invalid value for '{{name}}', must be one of {{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"); } + {{/isContainer}} {{/isEnum}} {{#hasValidation}} {{#maxLength}} - if (strlen(${{name}}) > {{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 (strlen(${{name}}) < {{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 (${{name}} > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{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 (${{name}} < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{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 (!preg_match("{{pattern}}", ${{name}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be conform to the pattern {{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->container['{{name}}'] = ${{name}}; @@ -320,4 +370,4 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this)); } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/model_test.mustache b/modules/swagger-codegen/src/main/resources/php/model_test.mustache index 52e0d830a23..4bd8f1d3dba 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_test.mustache @@ -9,7 +9,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -30,7 +30,7 @@ namespace {{invokerPackage}}; /** * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class {{classname}}Test extends \PHPUnit_Framework_TestCase diff --git a/modules/swagger-codegen/src/main/resources/php/phpunit.xml.mustache b/modules/swagger-codegen/src/main/resources/php/phpunit.xml.mustache new file mode 100644 index 00000000000..5de6fea575c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/phpunit.xml.mustache @@ -0,0 +1,21 @@ + + + + + {{apiTestPath}} + {{modelTestPath}} + + + + + + {{apiSrcPath}} + {{modelSrcPath}} + + + diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 08f2d835c4c..9f432447443 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -7,7 +7,9 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: {{appVersion}} - Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -51,6 +53,7 @@ import {{{packageName}}} Please follow the [installation procedure](#installation--usage) and then run the following: ```python +from __future__ import print_function import time import {{{packageName}}} from {{{packageName}}}.rest import ApiException @@ -67,7 +70,7 @@ from pprint import pprint {{{packageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} # create an instance of the API class -api_instance = {{{packageName}}}.{{{classname}}} +api_instance = {{{packageName}}}.{{{classname}}}() {{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} @@ -76,7 +79,7 @@ try: {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} pprint(api_response){{/returnType}} except ApiException as e: - print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) {{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index c866fc5805c..2d86c9de66c 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -127,43 +127,58 @@ class {{classname}}(object): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} - if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than or equal to `{{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}}`") {{/maximum}} {{#minimum}} - if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") + 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}}`") {{/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}}): + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{pattern}}}`") {{/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}}`") + {{/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}}`") + {{/minItems}} {{/hasValidation}} {{/allParams}} + + collection_formats = {} + resource_path = '{{path}}'.replace('{format}', 'json') path_params = {} {{#pathParams}} if '{{paramName}}' in params: - path_params['{{baseName}}'] = params['{{paramName}}'] + path_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/pathParams}} query_params = {} {{#queryParams}} if '{{paramName}}' in params: - query_params['{{baseName}}'] = params['{{paramName}}'] + query_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/queryParams}} header_params = {} {{#headerParams}} if '{{paramName}}' in params: - header_params['{{baseName}}'] = params['{{paramName}}'] + header_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/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}} + {{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/formParams}} body_params = None @@ -195,6 +210,7 @@ class {{classname}}(object): response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + 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 170cd05b4aa..0a5864a81af 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -19,17 +19,15 @@ Copyright 2016 SmartBear Software """ from __future__ import absolute_import + from . import models from .rest import RESTClientObject from .rest import ApiException import os import re -import sys -import urllib import json import mimetypes -import random import tempfile import threading @@ -37,14 +35,8 @@ from datetime import datetime from datetime import date # python 2 and python 3 compatibility library -from six import iteritems - -try: - # for python3 - from urllib.parse import quote -except ImportError: - # for python2 - from urllib import quote +from six import PY3, integer_types, iteritems, text_type +from six.moves.urllib.parse import quote from .configuration import Configuration @@ -103,34 +95,40 @@ class ApiClient(object): 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, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): - # headers parameters + # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.\ - replace('{' + k + '}', replacement) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + resource_path = resource_path.replace( + '{%s}' % k, quote(str(v))) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) - for k, v in iteritems(query_params)} + query_params = self.parameters_to_tuples(query_params, + collection_formats) # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) @@ -159,31 +157,16 @@ class ApiClient(object): if callback: callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return ( deserialized_data ); + return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - - - def to_path_value(self, obj): - """ - Takes value and turn it into a string suitable for inclusion in - the path, by url-encoding. - - :param obj: object or string value. - - :return string: quoted value. - """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) def sanitize_for_serialization(self, obj): """ Builds a JSON POST object. If obj is None, return None. - If obj is str, int, float, bool, return directly. + If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. @@ -193,9 +176,7 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, float, bool, tuple) - if sys.version_info < (3, 0): - types = types + (unicode,) + types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -203,6 +184,9 @@ class ApiClient(object): elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: @@ -227,7 +211,7 @@ class ApiClient(object): :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name. + deserialized object, or string of class name. :return: deserialized object. """ @@ -272,11 +256,13 @@ class ApiClient(object): if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) + elif klass == 'long': + klass = int if PY3 else long # for model types else: klass = eval('models.' + klass) - if klass in [int, float, str, bool]: + if klass in integer_types or klass in (float, str, bool): return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -290,7 +276,8 @@ class ApiClient(object): 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, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -312,6 +299,8 @@ class ApiClient(object): If provide this parameter, the request will be called asynchronously. :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. :return: If provide parameter callback, the request will be called asynchronously. @@ -323,7 +312,8 @@ class ApiClient(object): return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, - response_type, auth_settings, callback, _return_http_data_only) + response_type, auth_settings, callback, + _return_http_data_only, collection_formats) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -331,7 +321,8 @@ class ApiClient(object): header_params, body, post_params, files, response_type, auth_settings, - callback,_return_http_data_only)) + callback, _return_http_data_only, + collection_formats)) thread.start() return thread @@ -379,10 +370,41 @@ class ApiClient(object): body=body) else: raise ValueError( - "http method must be `GET`, `HEAD`," + "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) + def parameters_to_tuples(self, params, collection_formats): + """ + 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 + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in iteritems(params) if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. @@ -450,7 +472,7 @@ class ApiClient(object): Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. """ config = Configuration() @@ -466,7 +488,7 @@ class ApiClient(object): elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + querys.append((auth_setting['key'], auth_setting['value'])) else: raise ValueError( 'Authentication token must be in `query` or `header`' @@ -505,7 +527,7 @@ class ApiClient(object): :param data: str. :param klass: class literal. - :return: int, float, str, bool. + :return: int, long, float, str, bool. """ try: value = klass(data) @@ -573,6 +595,9 @@ class ApiClient(object): """ instance = klass() + if not instance.swagger_types: + return data + for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ 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 98dec04a393..f9a212c19e1 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -19,6 +19,7 @@ Method | HTTP request | Description ### Example ```python +from __future__ import print_statement import time import {{{packageName}}} from {{{packageName}}}.rest import ApiException @@ -45,7 +46,7 @@ try: {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} pprint(api_response){{/returnType}} except ApiException as e: - print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) ``` ### Parameters diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 3d2e8db228b..5ddc4ab7bca 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -3,19 +3,14 @@ {{>partial_header}} from __future__ import absolute_import -import base64 -import urllib3 -try: - import httplib -except ImportError: - # for python3 - import http.client as httplib +import urllib3 import sys import logging from six import iteritems +from six.moves import http_client as httplib def singleton(cls, *args, **kw): @@ -220,7 +215,7 @@ class Configuration(object): 'value': self.get_basic_auth_token() }, {{/isBasic}}{{#isOAuth}} - '{{name}}': + '{{name}}': { 'type': 'oauth2', 'in': 'header', diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index a08595db88a..68e064bd190 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -14,7 +14,7 @@ class {{classname}}(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self{{#readWriteVars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/readWriteVars}}): + def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): """ {{classname}} - a model defined in Swagger @@ -33,12 +33,10 @@ class {{classname}}(object): {{/hasMore}}{{/vars}} } -{{#readOnlyVars}} - self._{{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}} -{{/readOnlyVars}} -{{#readWriteVars}} +{{#vars}} self._{{name}} = {{name}} -{{/readWriteVars}} +{{/vars}} + {{#vars}}{{#-first}} {{/-first}} @property @@ -52,7 +50,6 @@ class {{classname}}(object): """ return self._{{name}} -{{^isReadOnly}} @{{name}}.setter def {{name}}(self, {{name}}): """ @@ -64,43 +61,71 @@ class {{classname}}(object): """ {{#isEnum}} allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] - if {{name}} not in allowed_values: +{{#isContainer}} +{{#isListContainer}} + if not set({{{name}}}).issubset(set(allowed_values)): raise ValueError( - "Invalid value for `{{name}}`, must be one of {0}" - .format(allowed_values) + "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" + .format(", ".join(map(str, set({{{name}}})-set(allowed_values))), + ", ".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))), + ", ".join(map(str, allowed_values))) + ) +{{/isMapContainer}} +{{/isContainer}} +{{^isContainer}} + if {{{name}}} not in allowed_values: + raise ValueError( + "Invalid value for `{{{name}}}` ({0}), must be one of {1}" + .format({{{name}}}, allowed_values) + ) +{{/isContainer}} {{/isEnum}} {{^isEnum}} -{{#hasValidation}} - - if not {{name}}: +{{#required}} + if {{name}} is None: raise ValueError("Invalid value for `{{name}}`, must not be `None`") +{{/required}} +{{#hasValidation}} {{#maxLength}} - if len({{name}}) > {{maxLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be less than `{{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}}`") {{/maxLength}} {{#minLength}} - if len({{name}}) < {{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}}`") {{/minLength}} {{#maximum}} - if {{name}} > {{maximum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{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}}`") {{/maximum}} {{#minimum}} - if {{name}} < {{minimum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{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}}`") {{/minimum}} {{#pattern}} - if not re.search('{{vendorExtensions.x-regex}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): - raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") + 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}}}`") {{/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}}`") +{{/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}}`") +{{/minItems}} {{/hasValidation}} {{/isEnum}} self._{{name}} = {{name}} -{{/isReadOnly}} {{/vars}} def to_dict(self): """ @@ -152,4 +177,4 @@ class {{classname}}(object): """ return not self == other {{/model}} -{{/models}} \ No newline at end of file +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 1a6cf193b6c..9bdddc91904 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -4,15 +4,16 @@ from __future__ import absolute_import -import sys import io import json import ssl import certifi import logging +import re # python 2 and python 3 compatibility library -from six import iteritems +from six import PY3 +from six.moves.urllib.parse import urlencode from .configuration import Configuration @@ -21,13 +22,6 @@ try: except ImportError: raise ImportError('Swagger python client requires urllib3.') -try: - # for python3 - from urllib.parse import urlencode -except ImportError: - # for python2 - from urllib import urlencode - logger = logging.getLogger(__name__) @@ -99,7 +93,7 @@ class RESTClientObject(object): :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, - `application/x-www-form-urlencode` + `application/x-www-form-urlencoded` and `multipart/form-data` """ method = method.upper() @@ -121,19 +115,19 @@ class RESTClientObject(object): if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': + if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) r = self.pool_manager.request(method, url, body=request_body, headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, headers=headers) - if headers['Content-Type'] == 'multipart/form-data': + elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type # which generated by urllib3 will be overwritten. del headers['Content-Type'] @@ -141,6 +135,19 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, 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 + elif isinstance(body, str): + request_body = body + r = self.pool_manager.request(method, url, + body=request_body, + 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.""" + raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, @@ -154,11 +161,11 @@ class RESTClientObject(object): # In the python 3, the response.data is bytes. # we need to decode it to string. - if sys.version_info > (3,): + if PY3: r.data = r.data.decode('utf8') # log response body - logger.debug("response body: %s" % r.data) + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache index fc5af8e0ae3..fb7b29b0107 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -94,6 +94,27 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) { qDebug() << "Can't set value because the target pointer is NULL"; } } + else if (QStringLiteral("QByteArray").compare(type) == 0) { + QByteArray **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + + *val = new QByteArray(QByteArray::fromBase64(QByteArray::fromStdString(obj.toString().toStdString()))); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } else if(type.startsWith("SWG") && obj.isObject()) { // complex type QJsonObject jsonObj = obj.toObject(); @@ -221,6 +242,10 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) { QDateTime* datetime = static_cast(value); output->insert(name, QJsonValue(datetime->toString(Qt::ISODate))); } + else if(QStringLiteral("QByteArray").compare(type) == 0) { + QByteArray* byteArray = static_cast(value); + output->insert(name, QJsonValue(QString(byteArray->toBase64()))); + } } void diff --git a/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache index 508b0ce7ede..d9d5db407be 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache @@ -4,7 +4,7 @@ class InitTables < ActiveRecord::Migration def change{{#models}}{{#model}} - create_table :{{classFilename}}, id: false do |t|{{#vars}}{{#isContainer}} + create_table "{{classFilename}}".pluralize.to_sym, id: false do |t|{{#vars}}{{#isContainer}} t.string :{{name}}{{/isContainer}}{{^isContainer}} t.{{datatype}} :{{{name}}}{{/isContainer}}{{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/rails5/model.mustache b/modules/swagger-codegen/src/main/resources/rails5/model.mustache index edfe9fac56c..8fc9455c2b7 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/model.mustache @@ -5,7 +5,7 @@ {{#models}}{{#model}} class {{classname}} < ApplicationRecord {{#requiredVars}} - validate_presence_of :{{name}} + validates_presence_of :{{name}} {{/requiredVars}}{{#vars}}{{#isListContainer}} serialize :{{name}}, Array{{/isListContainer}}{{#isMapContainer}} serialize :{{name}}, Hash{{/isMapContainer}}{{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/README.mustache b/modules/swagger-codegen/src/main/resources/ruby/README.mustache index 076192b75ce..abf26eeceda 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/README.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/README.mustache @@ -10,7 +10,9 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: {{appVersion}} - Package version: {{gemVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 7b333428899..7071e72e849 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -56,36 +56,48 @@ module {{moduleName}} {{/isEnum}} {{/required}} {{#hasValidation}} - {{#minLength}} - if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length > {{{maxLength}}} + {{#maxLength}} + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length > {{{maxLength}}} fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.' end - {{/minLength}} - {{#maxLength}} - if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length < {{{minLength}}} + {{/maxLength}} + {{#minLength}} + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length < {{{minLength}}} fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.' end - {{/maxLength}} + {{/minLength}} {{#maximum}} - if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} > {{{maximum}}} - fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{{maximum}}}.' + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.' end {{/maximum}} {{#minimum}} - if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} < {{{minimum}}} - fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than or equal to {{{minimum}}}.' + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.' end {{/minimum}} {{#pattern}} - if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} !~ Regexp.new({{{pattern}}}) - fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.' + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} !~ Regexp.new({{{pattern}}}) + fail ArgumentError, "invalid value for '{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:\"{{{paramName}}}\"]{{/required}}' when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}." end {{/pattern}} + {{#maxItems}} + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.length > {{{maxItems}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{{maxItems}}}.' + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.length < {{{minItems}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{{minItems}}}.' + end + + {{/minItems}} {{/hasValidation}} {{/allParams}} # resource path diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 496d52d3757..fcd4b3eebfa 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -20,7 +20,7 @@ module {{moduleName}} attr_accessor :default_headers # Initializes the ApiClient - # @option config [Configuration] Configuraiton for initializing the object, default to Configuration.default + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default def initialize(config = Configuration.default) @config = config @user_agent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/#{VERSION}/ruby{{/httpUserAgent}}" @@ -47,10 +47,18 @@ module {{moduleName}} end unless response.success? - fail ApiError.new(:code => response.code, - :response_headers => response.headers, - :response_body => response.body), - response.status_message + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end end if opts[:return_type] @@ -82,6 +90,9 @@ module {{moduleName}} update_params_for_auth! header_params, query_params, opts[:auth_names] {{/hasAuthMethods}} + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + req_opts = { :method => http_method, :headers => header_params, @@ -89,11 +100,13 @@ module {{moduleName}} :params_encoding => @config.params_encoding, :timeout => @config.timeout, :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, :sslcert => @config.cert_file, :sslkey => @config.key_file, :verbose => @config.debugging } + # set custom cert, if provided req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert if [:post, :patch, :put, :delete].include?(http_method) @@ -113,7 +126,7 @@ module {{moduleName}} # application/json; charset=UTF8 # APPLICATION/JSON # @param [String] mime MIME - # @return [Boolean] True if the MIME is applicaton/json + # @return [Boolean] True if the MIME is application/json def json_mime?(mime) !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end @@ -266,7 +279,7 @@ module {{moduleName}} # Update hearder and query params based on authentication settings. # # @param [Hash] header_params Header parameters - # @param [Hash] form_params Query parameters + # @param [Hash] query_params Query parameters # @param [String] auth_names Authentication scheme name def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache index fa6b3530d73..df32f34490f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache @@ -43,53 +43,6 @@ describe {{moduleName}}::ApiClient do end end - describe "#update_params_for_auth!" do - it "sets header api-key parameter with prefix" do - {{moduleName}}.configure do |c| - c.api_key_prefix['api_key'] = 'PREFIX' - c.api_key['api_key'] = 'special-key' - end - - api_client = {{moduleName}}::ApiClient.new - - config2 = {{moduleName}}::Configuration.new do |c| - c.api_key_prefix['api_key'] = 'PREFIX2' - c.api_key['api_key'] = 'special-key2' - end - api_client2 = {{moduleName}}::ApiClient.new(config2) - - auth_names = ['api_key', 'unknown'] - - header_params = {} - query_params = {} - api_client.update_params_for_auth! header_params, query_params, auth_names - expect(header_params).to eq({'api_key' => 'PREFIX special-key'}) - expect(query_params).to eq({}) - - header_params = {} - query_params = {} - api_client2.update_params_for_auth! header_params, query_params, auth_names - expect(header_params).to eq({'api_key' => 'PREFIX2 special-key2'}) - expect(query_params).to eq({}) - end - - it "sets header api-key parameter without prefix" do - {{moduleName}}.configure do |c| - c.api_key_prefix['api_key'] = nil - c.api_key['api_key'] = 'special-key' - end - - api_client = {{moduleName}}::ApiClient.new - - header_params = {} - query_params = {} - auth_names = ['api_key', 'unknown'] - api_client.update_params_for_auth! header_params, query_params, auth_names - expect(header_params).to eq({'api_key' => 'special-key'}) - expect(query_params).to eq({}) - end - end - describe "params_encoding in #build_request" do let(:config) { {{moduleName}}::Configuration.new } let(:api_client) { {{moduleName}}::ApiClient.new(config) } @@ -155,49 +108,18 @@ describe {{moduleName}}::ApiClient do expect(data).to be_instance_of(Hash) expect(data).to eq({:message => 'Hello'}) end - - it "handles Hash" do - api_client = {{moduleName}}::ApiClient.new - headers = {'Content-Type' => 'application/json'} - response = double('response', headers: headers, body: '{"pet": {"id": 1}}') - data = api_client.deserialize(response, 'Hash') - expect(data).to be_instance_of(Hash) - expect(data.keys).to eq([:pet]) - - pet = data[:pet] - expect(pet).to be_instance_of({{moduleName}}::Pet) - expect(pet.id).to eq(1) - end - - it "handles Hash>" do - api_client = {{moduleName}}::ApiClient.new - headers = {'Content-Type' => 'application/json'} - response = double('response', headers: headers, body: '{"data": {"pet": {"id": 1}}}') - result = api_client.deserialize(response, 'Hash>') - expect(result).to be_instance_of(Hash) - expect(result.keys).to match_array([:data]) - - data = result[:data] - expect(data).to be_instance_of(Hash) - expect(data.keys).to match_array([:pet]) - - pet = data[:pet] - expect(pet).to be_instance_of({{moduleName}}::Pet) - expect(pet.id).to eq(1) - end end describe "#object_to_hash" do it "ignores nils and includes empty arrays" do - api_client = {{moduleName}}::ApiClient.new - pet = {{moduleName}}::Pet.new - pet.id = 1 - pet.name = '' - pet.status = nil - pet.photo_urls = nil - pet.tags = [] - expected = {id: 1, name: '', tags: []} - expect(api_client.object_to_hash(pet)).to eq(expected) + # uncomment below to test object_to_hash for model + #api_client = {{moduleName}}::ApiClient.new + #_model = {{moduleName}}::ModelName.new + # update the model attribute below + #_model.id = 1 + # update the expected value (hash) below + #expected = {id: 1, name: '', tags: []} + #expect(api_client.object_to_hash(_model)).to eq(expected) end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index 0c15a9929f3..44a10211cc3 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -4,7 +4,7 @@ def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -35,7 +35,7 @@ when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -46,7 +46,7 @@ when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 7fe6c874c00..3d160d46511 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -68,7 +68,7 @@ module {{moduleName}} # Default to 0 (never times out). attr_accessor :timeout - ### TLS/SSL + ### TLS/SSL setting # Set this to false to skip verifying SSL certificate when calling API from https server. # Default to true. # @@ -77,13 +77,16 @@ module {{moduleName}} # @return [true, false] attr_accessor :verify_ssl - # Set this to customize parameters encoding of array parameter with multi collectionFormat. - # Default to nil. + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. # - # @see The params_encoding option of Ethon. Related source code: - # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 - attr_accessor :params_encoding + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + ### TLS/SSL setting # Set this to customize the certificate file to verify the peer. # # @return [String] the path to the certificate file @@ -92,12 +95,21 @@ module {{moduleName}} # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 attr_accessor :ssl_ca_cert + ### TLS/SSL setting # Client certificate file (for client certificate) attr_accessor :cert_file + ### TLS/SSL setting # Client private key file (for client certificate) attr_accessor :key_file + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + attr_accessor :inject_format attr_accessor :force_ending_format @@ -110,6 +122,7 @@ module {{moduleName}} @api_key_prefix = {} @timeout = 0 @verify_ssl = true + @verify_ssl_host = true @params_encoding = nil @cert_file = nil @key_file = nil diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache index 6ea22543491..2955eaa2503 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache @@ -8,21 +8,26 @@ describe {{moduleName}}::Configuration do let(:config) { {{moduleName}}::Configuration.default } before(:each) do - {{moduleName}}.configure do |c| - c.host = 'petstore.swagger.io' - c.base_path = 'v2' - end + # uncomment below to setup host and base_path + #require 'URI' + #uri = URI.parse("{{{basePath}}}") + #{{moduleName}}.configure do |c| + # c.host = uri.host + # c.base_path = uri.path + #end end describe '#base_url' do it 'should have the default value' do - expect(config.base_url).to eq('http://petstore.swagger.io/v2') + # uncomment below to test default value of the base path + #expect(config.base_url).to eq("{{{basePath}}}") end it 'should remove trailing slashes' do [nil, '', '/', '//'].each do |base_path| config.base_path = base_path - expect(config.base_url).to eq('http://petstore.swagger.io') + # uncomment below to test trailing slashes + #expect(config.base_url).to eq("{{{basePath}}}") end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 86d9a6e55d8..935fad7f61b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -17,6 +17,7 @@ Gem::Specification.new do |s| s.summary = "{{gemSummary}}{{^gemSummary}}{{{appName}}} Ruby Gem{{/gemSummary}}" s.description = "{{gemDescription}}{{^gemDescription}}{{{appDescription}}}{{^appDescription}}{{{appName}}} Ruby Gem{{/appDescription}}{{/gemDescription}}" s.license = "{{gemLicense}}{{^gemLicense}}{{{licenseInfo}}}{{^licenseInfo}}Apache 2.0{{/licenseInfo}}{{/gemLicense}}" + s.required_ruby_version = "{{{gemRequiredRubyVersion}}}{{^gemRequiredRubyVersion}}>= 1.9{{/gemRequiredRubyVersion}}" s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' s.add_runtime_dependency 'json', '~> 1.8', '>= 1.8.3' 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 0335500863f..00a75b25396 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 @@ -77,42 +77,58 @@ # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new - {{#hasValidation}} + {{#vars}} + {{#required}} if @{{{name}}}.nil? - fail ArgumentError, "{{{name}}} cannot be nil" + invalid_properties.push("invalid value for '{{{name}}}', {{{name}}} cannot be nil.") end - {{#minLength}} - if @{{{name}}}.to_s.length > {{{maxLength}}} + {{/required}} + {{#hasValidation}} + {{#maxLength}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} invalid_properties.push("invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}.") end - {{/minLength}} - {{#maxLength}} - if @{{{name}}}.to_s.length < {{{minLength}}} + {{/maxLength}} + {{#minLength}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} invalid_properties.push("invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}.") end - {{/maxLength}} + {{/minLength}} {{#maximum}} - if @{{{name}}} > {{{maximum}}} - invalid_properties.push("invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}.") + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + invalid_properties.push("invalid value for '{{{name}}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.") end {{/maximum}} {{#minimum}} - if @{{{name}}} < {{{minimum}}} - invalid_properties.push("invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}.") + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + invalid_properties.push("invalid value for '{{{name}}}', must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.") end {{/minimum}} {{#pattern}} - if @{{{name}}} !~ Regexp.new({{{pattern}}}) + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}}) invalid_properties.push("invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}.") end {{/pattern}} + {{#maxItems}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + invalid_properties.push("invalid value for '{{{name}}}', number of items must be less than or equal to {{{maxItems}}}." + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + invalid_properties.push("invalid value for '{{{name}}}', number of items must be greater than or equal to {{{minItems}}}." + end + + {{/minItems}} {{/hasValidation}} + {{/vars}} return invalid_properties end @@ -124,25 +140,33 @@ return false if @{{{name}}}.nil? {{/required}} {{#isEnum}} + {{^isContainer}} {{{name}}}_validator = EnumAttributeValidator.new('{{{datatype}}}', [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]) return false unless {{{name}}}_validator.valid?(@{{{name}}}) + {{/isContainer}} {{/isEnum}} {{#hasValidation}} - {{#minLength}} - return false if @{{{name}}}.to_s.length > {{{maxLength}}} - {{/minLength}} {{#maxLength}} - return false if @{{{name}}}.to_s.length < {{{minLength}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} {{/maxLength}} + {{#minLength}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} + {{/minLength}} {{#maximum}} - return false if @{{{name}}} > {{{maximum}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} {{/maximum}} {{#minimum}} - return false if @{{{name}}} < {{{minimum}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} {{/minimum}} {{#pattern}} - return false if @{{{name}}} !~ Regexp.new({{{pattern}}}) + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}}) {{/pattern}} + {{#maxItems}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + {{/maxItems}} + {{#minItems}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + {{/minItems}} {{/hasValidation}} {{/vars}} return true @@ -150,6 +174,7 @@ {{#vars}} {{#isEnum}} + {{^isContainer}} # Custom attribute writer method checking allowed values (enum). # @param [Object] {{{name}}} Object to be assigned def {{{name}}}=({{{name}}}) @@ -160,46 +185,61 @@ @{{{name}}} = {{{name}}} end + {{/isContainer}} {{/isEnum}} {{^isEnum}} {{#hasValidation}} # Custom attribute writer method with validation # @param [Object] {{{name}}} Value to be assigned def {{{name}}}=({{{name}}}) + {{#required}} if {{{name}}}.nil? fail ArgumentError, "{{{name}}} cannot be nil" end + {{/required}} - {{#minLength}} - if {{{name}}}.to_s.length > {{{maxLength}}} + {{#maxLength}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length > {{{maxLength}}} fail ArgumentError, "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}." end - {{/minLength}} - {{#maxLength}} - if {{{name}}}.to_s.length < {{{minLength}}} + {{/maxLength}} + {{#minLength}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length < {{{minLength}}} fail ArgumentError, "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}." end - {{/maxLength}} + {{/minLength}} {{#maximum}} - if {{{name}}} > {{{maximum}}} - fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}." + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}." end {{/maximum}} {{#minimum}} - if {{{name}}} < {{{minimum}}} - fail ArgumentError, "invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}." + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + fail ArgumentError, "invalid value for '{{{name}}}', must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}." end {{/minimum}} {{#pattern}} - if @{{{name}}} !~ Regexp.new({{{pattern}}}) + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} !~ Regexp.new({{{pattern}}}) fail ArgumentError, "invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}." end {{/pattern}} + {{#maxItems}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length > {{{maxItems}}} + fail ArgumentError, "invalid value for '{{{name}}}', number of items must be less than or equal to {{{maxItems}}}." + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length < {{{minItems}}} + fail ArgumentError, "invalid value for '{{{name}}}', number of items must be greater than or equal to {{{minItems}}}." + end + + {{/minItems}} @{{{name}}} = {{{name}}} end diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 584441ee14e..977f4e2b056 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -31,16 +31,13 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{#allParams}} * @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - def {{operationId}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { + def {{operationId}}({{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{#defaultValue}} /* = {{{defaultValue}}}*/{{/defaultValue}}{{/required}}{{^required}}Option[{{dataType}}]{{#defaultValue}} /* = {{{defaultValue}}}*/{{/defaultValue}}{{^defaultValue}} = None{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}: Option[{{returnType}}]{{/returnType}} = { // create path and map variables - val path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})) + val path = "{{path}}".replaceAll("\\{format\\}", "json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})){{/pathParams}} - {{/pathParams}} - - val contentTypes = List({{#consumes}}"{{{mediaType}}}", {{/consumes}}"application/json") + val contentTypes = List({{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}"application/json"{{/consumes}}) val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] @@ -51,29 +48,65 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", if ({{paramName}} == null) throw new Exception("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") {{/isPrimitiveType}} + {{#isString}} + if ({{paramName}} == null) throw new Exception("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") + + {{/isString}} {{/required}} {{/allParams}} - {{#queryParams}}if(String.valueOf({{paramName}}) != "null") queryParams += "{{baseName}}" -> {{paramName}}.toString + {{#queryParams}} + {{#required}} + queryParams += "{{baseName}}" -> {{paramName}}.toString + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => queryParams += "{{baseName}}" -> paramVal.toString) + {{/required}} {{/queryParams}} - {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}} + {{#headerParams}} + {{#required}} + headerParams += "{{baseName}}" -> {{paramName}} + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => headerParams += "{{baseName}}" -> paramVal) + {{/required}} {{/headerParams}} - var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} + var postBody: AnyRef = {{#bodyParam}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}.map(paramVal => paramVal){{/required}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - {{#formParams}}{{#notFile}} - mp.field("{{baseName}}", {{paramName}}.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) - {{/notFile}}{{#isFile}} + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart + {{#formParams}} + {{#notFile}} + {{#required}} + mp.field("{{baseName}}", {{paramName}}.toString, MediaType.MULTIPART_FORM_DATA_TYPE) + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => mp.field("{{baseName}}", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) + {{/required}} + {{/notFile}} + {{#isFile}} + {{#required}} mp.field("{{baseName}}", file.getName) mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)) - {{/isFile}}{{/formParams}} + {{/required}} + {{^required}} + file.map(fileVal => mp.field("{{baseName}}", fileVal.getName)) + {{paramName}}.map(paramVal => mp.bodyPart(new FileDataBodyPart("{{baseName}}", paramVal, MediaType.MULTIPART_FORM_DATA_TYPE))) + {{/required}} + {{/isFile}} + {{/formParams}} postBody = mp - } - else { + } else { {{#formParams}} - {{#notFile}}formParams += "{{baseName}}" -> {{paramName}}.toString(){{/notFile}} + {{#notFile}} + {{#required}} + formParams += "{{baseName}}" -> {{paramName}}.toString + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => formParams += "{{baseName}}" -> paramVal.toString) + {{/required}} + {{/notFile}} {{/formParams}} } diff --git a/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache index 72d362dafd8..5f192121eb4 100644 --- a/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/swagger-codegen/src/main/resources/scala/model.mustache b/modules/swagger-codegen/src/main/resources/scala/model.mustache index 40a9da8dc90..b6920ae9fd4 100644 --- a/modules/swagger-codegen/src/main/resources/scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/model.mustache @@ -1,16 +1,19 @@ {{>licenseInfo}} package {{package}} -{{#imports}}import {{import}} +{{#imports}} +import {{import}} {{/imports}} {{#models}} - {{#model}} - case class {{classname}} ( - {{#vars}}{{#description}}/* {{{description}}} */ - {{/description}}{{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}} {{/vars}} +) {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index 51256c42491..e6d80631460 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.8 + 1.5.9 1.0.5 1.0.0 2.4.2 diff --git a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache index afb0dd162d1..483ee4e5444 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache @@ -12,7 +12,7 @@ class ScalatraBootstrap extends LifeCycle { override def init(context: ServletContext) { implicit val system = ActorSystem("appActorSystem") try { - {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "/{{baseName}}/*") + {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "{{basePathWithoutHost}}/{{baseName}}/*") {{/apis}}{{/apiInfo}} context mount (new ResourcesApp, "/api-docs/*") } catch { diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache index bd3b40b8fac..7e0641396c7 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -16,14 +16,14 @@ import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintE import scala.collection.JavaConverters._ -class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet +class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "{{classname}}" - override protected val applicationName: Option[String] = Some("{{baseName}}") + override protected val applicationName: Option[String] = Some("{{basePathWithoutHost}}/{{baseName}}") before() { contentType = formats("json") @@ -35,16 +35,15 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") summary "{{{summary}}}" - parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}) + parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ) - {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { + {{httpMethod}}("{{{vendorExtensions.x-scalatra-path}}}",operation({{nickname}}Operation)) { {{#allParams}} {{#isFile}}val {{paramName}} = fileParams("{{paramName}}"){{/isFile}} {{^isFile}}{{#isPathParam}} val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)){{/isPathParam}} - {{>queryParamOperation}}{{>headerParamOperation}}{{>formParamMustache}}{{>bodyParam}} + {{>queryParamOperation}}{{>headerParamOperation}}{{>formParamMustache}}{{>bodyParamOperation}} {{/isFile}} println("{{paramName}}: " + {{paramName}}) {{/allParams}} @@ -52,4 +51,4 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet {{/operation}} {{/operations}} -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache index c1a2f2585de..cf14e9a7362 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache @@ -6,10 +6,13 @@ package {{package}} {{/imports}} {{#models}} - {{#model}} case class {{classname}} ( - {{#vars}}{{name}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}} + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{name}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} ) {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/silex/index.mustache b/modules/swagger-codegen/src/main/resources/silex/index.mustache index 9fbfca6049e..0ace4d41fda 100644 --- a/modules/swagger-codegen/src/main/resources/silex/index.mustache +++ b/modules/swagger-codegen/src/main/resources/silex/index.mustache @@ -12,7 +12,7 @@ $app = new Silex\Application(); {{#operations}} {{#operation}} -$app->{{httpMethod}}('{{path}}', function(Application $app, Request $request{{#pathParams}}, ${{paramName}}{{/pathParams}}) { +$app->{{httpMethod}}('{{basePathWithoutHost}}{{path}}', function(Application $app, Request $request{{#pathParams}}, ${{paramName}}{{/pathParams}}) { {{#queryParams}}${{paramName}} = $request->get('{{paramName}}');{{newline}} {{/queryParams}} {{#formParams}}${{paramName}} = $request->get('{{paramName}}');{{newline}} {{/formParams}} return new Response('How about implementing {{nickname}} as a {{httpMethod}} method ?'); diff --git a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache index 27830feed31..55230231f2c 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache @@ -18,7 +18,7 @@ MyApp.add_route('{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', { "dataType" => "{{dataType}}", "paramType" => "query", {{#collectionFormat}}"collectionFormat" => "{{collectionFormat}}",{{/collectionFormat}} - "allowableValues" => "{{allowableValues}}", + "allowableValues" => "{{^isContainer}}{{{allowableValues.values}}}{{/isContainer}}", {{#defaultValue}}"defaultValue" => "{{{defaultValue}}}"{{/defaultValue}} }, {{/queryParams}} diff --git a/modules/swagger-codegen/src/main/resources/slim/index.mustache b/modules/swagger-codegen/src/main/resources/slim/index.mustache index 383094821dd..127786c4325 100644 --- a/modules/swagger-codegen/src/main/resources/slim/index.mustache +++ b/modules/swagger-codegen/src/main/resources/slim/index.mustache @@ -15,7 +15,7 @@ $app = new Slim\App(); * Notes: {{notes}} {{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} */ -$app->{{httpMethod}}('{{path}}', function($request, $response, $args) { +$app->{{httpMethod}}('{{basePathWithoutHost}}{{path}}', function($request, $response, $args) { {{#hasHeaderParams}}$headers = $request->getHeaders();{{/hasHeaderParams}} {{#hasQueryParams}}$queryParams = $request->getQueryParams(); {{#queryParams}}${{paramName}} = $queryParams['{{paramName}}'];{{newline}} {{/queryParams}}{{/hasQueryParams}} diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index 5a9f1f7a278..9ba749ab69e 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -37,6 +37,9 @@ public class RequestBuilder { let method: String let URLString: String + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 2faa0a6f24d..4ea47d8926c 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -12,8 +12,33 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { } } +public struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = dispatch_queue_create("SynchronizedDictionary", DISPATCH_QUEUE_CONCURRENT) + + public subscript(key: K) -> V? { + get { + var value: V? + + dispatch_sync(queue) { + value = self.dictionary[key] + } + + return value + } + + set { + dispatch_barrier_sync(queue) { + self.dictionary[key] = newValue + } + } + } + +} + // Store manager to retain its reference -private var managerStore: [String: Alamofire.Manager] = [:] +private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { @@ -57,15 +82,22 @@ class AlamofireRequestBuilder: RequestBuilder { encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: { encodingResult in switch encodingResult { - case .Success(let upload, _, _): - self.processRequest(upload, managerId, completion) + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): - completion(response: nil, error: encodingError) + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) } } ) } else { - processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) } } @@ -75,30 +107,99 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.validate().responseJSON(options: .AllowFragments) { response in - managerStore.removeValueForKey(managerId) + let cleanupRequest = { + managerStore[managerId] = nil + } - if response.result.isFailure { - completion(response: nil, error: response.result.error) - return - } + let validatedRequest = request.validate() - if () is T { - completion(response: Response(response: response.response!, body: () as! T), error: nil) - return - } - if let json: AnyObject = response.result.value { - let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), error: nil) - return - } else if "" is T { - // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release - // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), error: nil) - return - } + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) + case is NSData.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) + } } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index a0906ba5969..101df9a7e04 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,3 @@ github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}} -github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} +github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}}{{#useRxSwift}} +github "ReactiveX/RxSwift" ~> 2.0{{/useRxSwift}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index 54a1f127ef7..27253b6d95f 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -59,11 +59,17 @@ extension Dictionary: JSONEncodable { } } +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} private let dateFormatter: NSDateFormatter = { - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt }() extension NSDate: JSONEncodable { @@ -72,6 +78,12 @@ extension NSDate: JSONEncodable { } } +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + {{#usePromiseKit}}extension RequestBuilder { public func execute() -> Promise> { let deferred = Promise>.pendingPromise() diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 17b9c2cd276..2d7c9094091 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -10,18 +10,22 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + public class Response { public let statusCode: Int public let header: [String: String] - public let body: T + public let body: T? - public init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T?) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { @@ -62,9 +66,15 @@ class Decoders { if T.self is Int64.Type && source is NSNumber { return source.longLongValue as! T; } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } if source is T { return source as! T } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } let key = "\(T.self)" if let decoder = decoders[key] { diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 3af6910a094..62f2b762c07 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -1,20 +1,36 @@ Pod::Spec.new do |s| - s.name = '{{projectName}}'{{#projectDescription}} - s.summary = '{{projectDescription}}'{{/projectDescription}} + s.name = '{{projectName}}' s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' - s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} - s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} - s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} - s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} - s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} - s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} - s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} - s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} - s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} - s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} - s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} - s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 3.1.5' + s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}} + {{#podAuthors}} + s.authors = '{{podAuthors}}' + {{/podAuthors}} + {{#podSocialMediaURL}} + s.social_media_url = '{{podSocialMediaURL}}' + {{/podSocialMediaURL}} + {{#podDocsetURL}} + s.docset_url = '{{podDocsetURL}}' + {{/podDocsetURL}} + s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}} + s.homepage = '{{podHomepage}}{{^podHomepage}}https://github.com/swagger-api/swagger-codegen{{/podHomepage}}' + s.summary = '{{podSummary}}{{^podSummary}}{{projectName}} Swift SDK{{/podSummary}}' + {{#podDescription}} + s.description = '{{podDescription}}' + {{/podDescription}} + {{#podScreenshots}} + s.screenshots = {{& podScreenshots}} + {{/podScreenshots}} + {{#podDocumentationURL}} + s.documentation_url = '{{podDocumentationURL}}' + {{/podDocumentationURL}} + s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift' + {{#usePromiseKit}} + s.dependency 'PromiseKit', '~> 3.1.1' + {{/usePromiseKit}} + {{#useRxSwift}} + s.dependency 'RxSwift', '~> 2.0' + {{/useRxSwift}} + s.dependency 'Alamofire', '~> 3.4.1' end diff --git a/modules/swagger-codegen/src/main/resources/swift/_param.mustache b/modules/swagger-codegen/src/main/resources/swift/_param.mustache new file mode 100644 index 00000000000..6d2de20a655 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/_param.mustache @@ -0,0 +1 @@ +"{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}.rawValue{{/isContainer}}{{/isEnum}}{{#isDate}}{{^required}}?{{/required}}.encodeToJSON(){{/isDate}}{{#isDateTime}}{{^required}}?{{/required}}.encodeToJSON(){{/isDateTime}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 8a9dc9077e7..24b8905f2c5 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -6,7 +6,8 @@ // import Alamofire{{#usePromiseKit}} -import PromiseKit{{/usePromiseKit}} +import PromiseKit{{/usePromiseKit}}{{#useRxSwift}} +import RxSwift{{/useRxSwift}} {{#swiftUseApiNamespace}} extension {{projectName}}API { @@ -62,6 +63,28 @@ public class {{classname}}: APIBase { return deferred.promise } {{/usePromiseKit}} +{{#useRxSwift}} + /** + {{#summary}} + {{{summary}}} + {{/summary}}{{#allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + - returns: Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + */ + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + return Observable.create { observer -> Disposable in + {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next({{#returnType}}data!{{/returnType}})) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } +{{/useRxSwift}} /** {{#summary}} @@ -84,14 +107,14 @@ public class {{classname}}: APIBase { */ public class func {{operationId}}WithRequestBuilder({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{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.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .LiteralSearch, range: nil){{/pathParams}} + path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", withString: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .LiteralSearch, range: nil){{/pathParams}} let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} - "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} - "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}.rawValue{{/isContainer}}{{/isEnum}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache index 1bbef2d1322..56732788f62 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache @@ -13,13 +13,13 @@ namespace {{package}} { {{/description}} export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{#vars}} - {{#description}} /** * {{{description}}} */ {{/description}} - "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + {{/vars}} } @@ -27,9 +27,12 @@ namespace {{package}} { export namespace {{classname}} { {{#vars}} {{#isEnum}} - - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}'{{^-last}},{{/-last}}{{/values}}{{/allowableValues}} + export enum {{enumName}} { + {{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} } {{/isEnum}} {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache index 73736fefb0c..218831c42d1 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache @@ -31,3 +31,14 @@ npm install PATH_TO_GENERATED_PACKAGE --save In your angular2 project: TODO: paste example. + +### 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'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 15bb69c5b84..6980d8f7821 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,14 +1,19 @@ {{>licenseInfo}} -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; +import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ {{#operations}} -'use strict'; {{#description}} /** @@ -18,12 +23,16 @@ import 'rxjs/Rx'; @Injectable() export class {{classname}} { protected basePath = '{{basePath}}'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); + public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (basePath) { this.basePath = basePath; } + if (configuration) { + this.configuration = configuration; + } } {{#operation}} @@ -32,12 +41,30 @@ export class {{classname}} { * {{notes}} {{#allParams}}* @param {{paramName}} {{description}} {{/allParams}}*/ - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - const path = this.basePath + '{{path}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + return this.{{nickname}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}extraHttpRequestParams) + .map((response: Response) => { + if (response.status === 204) { + return undefined; + } else { + return response.json(); + } + }); + } + +{{/operation}} + +{{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ + public {{nickname}}WithHttpInfo({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any): Observable { + const path = this.basePath + `{{path}}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 {{#hasFormParams}} let formParams = new URLSearchParams(); @@ -52,44 +79,91 @@ export class {{classname}} { {{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters.set('{{baseName}}', {{paramName}}); + queryParameters.set('{{baseName}}', {{paramName}}); } - {{/queryParams}} -{{#headerParams}} - headerParams.set('{{baseName}}', {{paramName }}); -{{/headerParams}} -{{#hasFormParams}} - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); +{{#headers}} + headers.set('{{baseName}}', String({{paramName}})); + +{{/headers}} + // to determine the Content-Type header + let consumes: string[] = [ + {{#consumes}} + '{{{mediaType}}}'{{#hasMore}}, {{/hasMore}} + {{/consumes}} + ]; + + // to determine the Accept header + let produces: string[] = [ + {{#produces}} + '{{{mediaType}}}'{{#hasMore}}, {{/hasMore}} + {{/produces}} + ]; + +{{#authMethods}} + // authentication ({{name}}) required +{{#isApiKey}} +{{#isKeyInHeader}} + if (this.configuration.apiKey) + { + headers.set('{{keyParamName}}', this.configuration.apiKey); + } +{{/isKeyInHeader}} +{{#isKeyInQuery}} + if (this.configuration.apiKey) + { + formParams.set('{{keyParamName}}', this.configuration.apiKey); + } +{{/isKeyInQuery}} +{{/isApiKey}} +{{#isBasic}} + // http basic authentication required + if (this.configuration.username || this.configuration.password) + { + headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); + } +{{/isBasic}} +{{#isOAuth}} + // oauth required + if (this.configuration.accessToken) + { + headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + } +{{/isOAuth}} +{{/authMethods}} + +{{#hasFormParams}} + headers.set('Content-Type', 'application/x-www-form-urlencoded'); {{/hasFormParams}} -{{#formParams}} - formParams['{{baseName}}'] = {{paramName}}; +{{#bodyParam}} + headers.set('Content-Type', 'application/json'); +{{/bodyParam}} + +{{#formParams}} + if ({{paramName}} !== undefined) { + formParams.set('{{baseName}}', {{paramName}}); + } {{/formParams}} - let requestOptions: RequestOptionsArgs = { - method: '{{httpMethod}}', - headers: headerParams, - search: queryParameters - }; - {{#bodyParam}} - requestOptions.body = JSON.stringify({{paramName}}); - {{/bodyParam}} - {{#hasFormParams}} - requestOptions.body = formParams.toString(); - {{/hasFormParams}} - - return this.http.request(path, requestOptions) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: {{httpMethod}}, + headers: headers, +{{#bodyParam}} + body: {{paramName}} == null ? '' : JSON.stringify({{paramName}}), // https://github.com/angular/angular/issues/10612 +{{/bodyParam}} +{{#hasFormParams}} + body: formParams.toString(), +{{/hasFormParams}} + search: queryParameters, + responseType: ResponseContentType.Json + }); + + return this.http.request(path, requestOptions); } {{/operation}} } -{{/operations}} +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache new file mode 100644 index 00000000000..94989933b63 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache @@ -0,0 +1,6 @@ +export class Configuration { + apiKey: string; + username: string; + password: string; + accessToken: string; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache index 557365516ad..d097c728017 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache @@ -1,2 +1,4 @@ export * from './api/api'; -export * from './model/models'; \ No newline at end of file +export * from './model/models'; +export * from './variables'; +export * from './configuration'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache index 6ae9b8c48cd..d0e544c4e2f 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache @@ -1,7 +1,6 @@ {{>licenseInfo}} {{#models}} {{#model}} -'use strict'; import * as models from './models'; {{#description}} @@ -10,24 +9,30 @@ import * as models from './models'; */ {{/description}} export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent}}{ - {{#additionalPropertiesType}}[key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}};{{/additionalPropertiesType}} -{{#vars}} +{{#additionalPropertiesType}} + [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; +{{/additionalPropertiesType}} +{{#vars}} {{#description}} /** * {{{description}}} */ {{/description}} - {{name}}?: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + {{/vars}} } {{#hasEnums}} export namespace {{classname}} { {{#vars}} {{#isEnum}} - - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}',{{/values}}{{/allowableValues}} + export enum {{enumName}} { + {{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} } {{/isEnum}} {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index 70cb98cce7e..5978cd38d32 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -7,33 +7,36 @@ "swagger-client" ], "license": "Apache-2.0", - "files": [ - "lib" - ], - "main": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "dist/index.js", + "typings": "dist/index.d.ts", "scripts": { - "build": "typings install && tsc" + "build": "typings install && tsc --outDir dist/", + "postinstall": "npm run build" }, "peerDependencies": { - "@angular/core": "^2.0.0-rc.1", - "@angular/http": "^2.0.0-rc.1" + "@angular/core": "^2.0.0-rc.5", + "@angular/http": "^2.0.0-rc.5", + "@angular/common": "^2.0.0-rc.5", + "@angular/compiler": "^2.0.0-rc.5", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "5.0.0-beta.6", + "zone.js": "^0.6.17" }, "devDependencies": { - "@angular/common": "^2.0.0-rc.1", - "@angular/compiler": "^2.0.0-rc.1", - "@angular/core": "^2.0.0-rc.1", - "@angular/http": "^2.0.0-rc.1", - "@angular/platform-browser": "^2.0.0-rc.1", - "@angular/platform-browser-dynamic": "^2.0.0-rc.1", - "core-js": "^2.3.0", - "rxjs": "^5.0.0-beta.6", - "zone.js": "^0.6.12", + "@angular/core": "^2.0.0-rc.5", + "@angular/http": "^2.0.0-rc.5", + "@angular/common": "^2.0.0-rc.5", + "@angular/compiler": "^2.0.0-rc.5", + "@angular/platform-browser": "^2.0.0-rc.5", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "5.0.0-beta.6", + "zone.js": "^0.6.17", "typescript": "^1.8.10", - "typings": "^0.8.1", - "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0" - }{{#npmRepository}}, + "typings": "^1.3.2" + }{{#npmRepository}},{{/npmRepository}} +{{#npmRepository}} "publishConfig":{ "registry":"{{npmRepository}}" } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache index 0848dcffe31..507c40e5cbe 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache @@ -1,5 +1,5 @@ { - "ambientDependencies": { - "core-js": "registry:dt/core-js#0.0.0+20160317120654" + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160725163759" } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache new file mode 100644 index 00000000000..27b987e9b23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache @@ -0,0 +1,3 @@ +import { OpaqueToken } from '@angular/core'; + +export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file 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 38c1fa34458..d501432df28 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -27,7 +27,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ * {{{description}}} */ {{/description}} - '{{name}}': {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + '{{name}}': {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } @@ -35,8 +35,12 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ export namespace {{classname}} { {{#vars}} {{#isEnum}} - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{datatypeWithEnum}}_{{.}} = '{{.}}'{{^-last}},{{/-last}}{{/values}}{{/allowableValues}} + export enum {{enumName}} { + {{#allowableValues}} + {{#enumVars}} + {{name}} = {{{value}}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} } {{/isEnum}} {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/undertow/README.mustache b/modules/swagger-codegen/src/main/resources/undertow/README.mustache new file mode 100644 index 00000000000..9f1e36dd163 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/README.mustache @@ -0,0 +1,28 @@ +# Swagger Undertow Server + +## Start server + +Run with + +``` +mvn package exec:exec +`` + +## Test + +By default, all endpoints are protected by OAuth jwt token verifier. It can be turned off with config change through for development. + + +In order to access the server, there is a long lived token below issued by my +oauth2 server [undertow-server-oauth2](https://github.com/networknt/undertow-server-oauth2) + +``` +Bearer eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTc4ODEzMjczNSwianRpIjoiNWtyM2ZWOHJaelBZNEJrSnNYZzFpQSIsImlhdCI6MTQ3Mjc3MjczNSwibmJmIjoxNDcyNzcyNjE1LCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJkZGNhZjBiYS0xMTMxLTIyMzItMzMxMy1kNmYyNzUzZjI1ZGMiLCJzY29wZSI6WyJhcGkuciIsImFwaS53Il19.gteJiy1uao8HLeWRljpZxHWUgQfofwmnFP-zv3EPUyXjyCOy3xclnfeTnTE39j8PgBwdFASPcDLLk1YfZJbsU6pLlmYXLtdpHDBsVmIRuch6LFPCVQ3JdqSQVci59OhSK0bBThGWqCD3UzDI_OnX4IVCAahcT9Bu94m5u_H_JNmwDf1XaP3Lt4I34buYMuRD9stchsnZi-tuIRkL13FARm1XA9aPZUMUXFdedBWDXo1zMREQ_qCJXOpaZDJM9Im0rIkq9wTEVU00pbRp_Vcdya3dfkFteBMHiwFVt6VNQaco5BXURDAIzXidwQxNEbX1ek03wra8AIani65ZK7fy_w +``` + +Postman is the best tool to test REST APIs + +Add "Authorization" header with value as above token and a dummy message will return from the generated stub. + + + diff --git a/modules/swagger-codegen/src/main/resources/undertow/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/undertow/bodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/enumClass.mustache b/modules/swagger-codegen/src/main/resources/undertow/enumClass.mustache new file mode 100644 index 00000000000..0867107d993 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/enumClass.mustache @@ -0,0 +1,17 @@ + + public enum {{{datatypeWithEnum}}} { + {{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private String value; + + {{{datatypeWithEnum}}}(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } diff --git a/modules/swagger-codegen/src/main/resources/undertow/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/undertow/enumOuterClass.mustache new file mode 100644 index 00000000000..aca7bd48c14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/enumOuterClass.mustache @@ -0,0 +1,42 @@ +{{#jackson}} + import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + +/** +* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} +*/ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { +{{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} +{{/gson}} +{{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} +{{/gson}} + +private {{{dataType}}} value; + +{{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { +this.value = value; +} + +@Override +@JsonValue +public String toString() { +return String.valueOf(value); +} + +@JsonCreator +public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { +for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { +if (String.valueOf(b.value).equals(text)) { +return b; +} +} +return null; +} +} diff --git a/modules/swagger-codegen/src/main/resources/undertow/formParams.mustache b/modules/swagger-codegen/src/main/resources/undertow/formParams.mustache new file mode 100644 index 00000000000..e44ab167e8f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/undertow/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/handler.mustache b/modules/swagger-codegen/src/main/resources/undertow/handler.mustache new file mode 100644 index 00000000000..c6830c0cd97 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/handler.mustache @@ -0,0 +1,34 @@ +package io.swagger.handler; + +import com.networknt.config.Config; +import com.networknt.server.HandlerProvider; +import io.undertow.Handlers; +import io.undertow.server.HttpHandler; +import io.undertow.server.HttpServerExchange; +import io.undertow.util.Methods; + +public class PathHandlerProvider implements HandlerProvider { + + public HttpHandler getHandler() { + HttpHandler handler = Handlers.routing() + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + + .add(Methods.{{httpMethod}}, "{{basePathWithoutHost}}{{path}}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("{{operationId}}"); + } + }) + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + ; + return handler; + } +} + diff --git a/modules/swagger-codegen/src/main/resources/undertow/headerParams.mustache b/modules/swagger-codegen/src/main/resources/undertow/headerParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/inflector.mustache b/modules/swagger-codegen/src/main/resources/undertow/inflector.mustache new file mode 100644 index 00000000000..87fc5581316 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/inflector.mustache @@ -0,0 +1,13 @@ +controllerPackage: {{invokerPackage}} +modelPackage: {{modelPackage}} +swaggerUrl: ./src/main/swagger/swagger.yaml +modelMappings: + # to enable explicit mappings, use this syntax: + DefinitionFromSwaggerSpecification: fully.qualified.path.to.Model + {{#models}}{{#model}}{{classname}} : {{modelPackage}}.{{classname}}{{/model}} + {{/models}} + +entityProcessors: + - json + - xml + - yaml \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/model.mustache b/modules/swagger-codegen/src/main/resources/undertow/model.mustache new file mode 100644 index 00000000000..b9512d2b83c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/model.mustache @@ -0,0 +1,16 @@ +package {{package}}; + +import java.util.Objects; +{{#imports}}import {{import}}; +{{/imports}} + +{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} +{{#models}} +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +{{#isEnum}}{{>enumOuterClass}}{{/isEnum}} +{{^isEnum}}{{>pojo}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/undertow/pathParams.mustache b/modules/swagger-codegen/src/main/resources/undertow/pathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache b/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache new file mode 100644 index 00000000000..58bfed16381 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache @@ -0,0 +1,73 @@ +{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} +{{>generatedAnnotation}} +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>enumClass}}{{/items}}{{/items.isEnum}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + + {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{baseName}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} + return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/swagger-codegen/src/main/resources/undertow/pom.mustache b/modules/swagger-codegen/src/main/resources/undertow/pom.mustache new file mode 100644 index 00000000000..f351376888b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/pom.mustache @@ -0,0 +1,189 @@ + + + org.sonatype.oss + oss-parent + 5 + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.2.0 + + + + 1.8 + UTF-8 + 0.1.1 + 2.8.2 + 1.7.21 + 0.5.2 + 4.5.3 + 2.6 + 2.5 + 1.10 + 1.2 + 3.1.2 + 1.1.7 + 4.12 + 2.1.0-beta.124 + 1.4.0.Final + 2.2.0 + 4.5.2 + 4.1.2 + 1.5.10 + + + + + com.networknt + config + ${version.framework} + + + com.networknt + utility + ${version.framework} + + + com.networknt + security + ${version.framework} + + + com.networknt + client + ${version.framework} + + + com.networknt + audit + ${version.framework} + + + com.networknt + info + ${version.framework} + + + com.networknt + validator + ${version.framework} + + + com.networknt + server + ${version.framework} + + + + com.fasterxml.jackson.core + jackson-databind + ${version.jackson} + + + com.fasterxml.jackson.core + jackson-core + ${version.jackson} + + + com.jayway.jsonpath + json-path + ${version.jsonpath} + + + ch.qos.logback + logback-classic + ${version.logback} + + + io.undertow + undertow-core + ${version.undertow} + + + io.swagger + swagger-annotations + ${version.swagger} + + + + + junit + junit + ${version.junit} + test + + + org.apache.httpcomponents + httpclient + ${version.httpclient} + test + + + + + + + install + target + ${project.artifactId}-${project.version} + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.3 + + + package + + shade + + + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + com.networknt.server.Server + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + java + + -jar + target/${project.build.finalName}.jar + + + + + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + diff --git a/modules/swagger-codegen/src/main/resources/undertow/primary.crt b/modules/swagger-codegen/src/main/resources/undertow/primary.crt new file mode 100644 index 00000000000..34f9272f81e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/primary.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDmzCCAoOgAwIBAgIEHnAgtDANBgkqhkiG9w0BAQsFADB+MQswCQYDVQQGEwJDQTEQMA4GA1UE +CBMHT250YXJpbzEUMBIGA1UEBxMLTWlzc2lzc2F1Z2ExJjAkBgNVBAoTHU5ldHdvcmsgTmV3IFRl +Y2hub2xvZ2llcyBJbmMuMQwwCgYDVQQLEwNERVYxETAPBgNVBAMTCFN0ZXZlIEh1MB4XDTE2MDkw +MTE2MTYxNVoXDTI2MDcxMTE2MTYxNVowfjELMAkGA1UEBhMCQ0ExEDAOBgNVBAgTB09udGFyaW8x +FDASBgNVBAcTC01pc3Npc3NhdWdhMSYwJAYDVQQKEx1OZXR3b3JrIE5ldyBUZWNobm9sb2dpZXMg +SW5jLjEMMAoGA1UECxMDREVWMREwDwYDVQQDEwhTdGV2ZSBIdTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBALrlxMtDb60DogElf4TBz504tRheZimAE0dJL/Yby4nacJdqvc5l4z+WWpDf +rI9krQ2Yi9yvhwAP+PrR6gWcIqWP4cpNE7XIAUDgr4CtyI7CptT/lpjtbkz4DGCMmaeDn0jqHqJt +SeSZGfwVu5zAGm8n4sHatjnnxBI/iWzkTII3V4xv0WeK37szNTEd+ly2ag7n2IV5zNnYmqZTeMQm +J2ENS+IwAG3ENtiVtrVTx/2bGtqutJjtdxsN58/cUG/guRyMT6OPI8Yi3ZzevdvRbxadyhEl/Kaw +6vJcdxmJI3tp4lx+p6sAxOWa7aapJe4JxutAQqzv0GKdVjoHKQ1wB60CAwEAAaMhMB8wHQYDVR0O +BBYEFIPF9SBd06RWU1eDL73CKfy01lavMA0GCSqGSIb3DQEBCwUAA4IBAQAoaKZGOak3Upz/ordF +slZoJuZlCu7jnKQEjYwHf3DNxcd1WmgFPtMcna6pW0VUxPIfidEA6VCMsGoK1RvshB0SjrRdCht6 +5qPXs9kV3NW0WvMiwDSYZZ9HgaZ9efTe5E9Fzc7ltKrE43L6k8NJcaEEWEdpdjFbrAqH4I+j/Vro +K3OhIo062fXjas5ipL4gF+3ECImjWzirQP8UiAfM0/36x7rtAu3btH/qI9hSyx39LBPPE5AsDJZ4 +dSMwNTW1gqmBAZIj+zQ/RD5dyWfPwON7Q+t96YbK6WBuYo0xy+I+PjcUgrWYWP3N24hlq8ZBIei+ +BudoEVJlIlmS0aRCuP8n +-----END CERTIFICATE----- diff --git a/modules/swagger-codegen/src/main/resources/undertow/queryParams.mustache b/modules/swagger-codegen/src/main/resources/undertow/queryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/security.json b/modules/swagger-codegen/src/main/resources/undertow/security.json new file mode 100644 index 00000000000..400070d0a2d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/security.json @@ -0,0 +1,13 @@ +{ + "description": "security configuration", + "enableVerifyJwt": false, + "jwt": { + "certificate": [ + "oauth/primary.crt" + ], + "clockSkewInSeconds": 60 + }, + "logJwtToken": true, + "logClientUserScope": false, + "enableVerifyScope": true +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/server.json b/modules/swagger-codegen/src/main/resources/undertow/server.json new file mode 100644 index 00000000000..14d16ce289a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/server.json @@ -0,0 +1,5 @@ +{ + "description": "server config", + "ip": "0.0.0.0", + "port": 8080 +} diff --git a/modules/swagger-codegen/src/main/resources/undertow/service.mustache b/modules/swagger-codegen/src/main/resources/undertow/service.mustache new file mode 100644 index 00000000000..e6f7ef0b3e5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/service.mustache @@ -0,0 +1 @@ +io.swagger.handler.PathHandlerProvider \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/undertow/swagger.mustache b/modules/swagger-codegen/src/main/resources/undertow/swagger.mustache new file mode 100644 index 00000000000..0a7a2006155 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/undertow/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-json}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index bd0fcc168cd..e96ad452806 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -1,5 +1,6 @@ package io.swagger.codegen; +import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Swagger; import io.swagger.models.properties.Property; @@ -111,9 +112,8 @@ public void enumQueryParameterTest() { final CodegenParameter statusParam = op.queryParams.get(0); Assert.assertEquals(statusParam.datatypeWithEnum, "List"); Assert.assertEquals(statusParam.baseType, "String"); - // currently there's no way to tell if the inner type of a list is a enum - //Assert.assertTrue(statusParam.isEnum); - //Assert.assertEquals(statusParam._enum.size(), 3); + Assert.assertTrue(statusParam.isEnum); + Assert.assertEquals(((List)statusParam.allowableValues.get("values")).size(), 3); } @@ -188,6 +188,129 @@ public void discriminatorTest() { Assert.assertEquals(op.discriminator, "className"); } + @Test(description = "handle simple composition") + public void simpleCompositionTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("SimpleComposition"); + CodegenModel composed = codegen.fromModel("SimpleComposition", model, swagger.getDefinitions()); + + Assert.assertEquals(composed.vars.size(), 3); + Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(composed.vars.get(1).baseName, "modelTwoProp"); + Assert.assertEquals(composed.vars.get(2).baseName, "simpleCompositionProp"); + Assert.assertNull(composed.parent); + } + + @Test(description = "handle multi level composition") + public void multiCompositionTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("CompositionOfSimpleComposition"); + CodegenModel composed = codegen.fromModel("CompositionOfSimpleComposition", model, swagger.getDefinitions()); + + Assert.assertEquals(composed.vars.size(), 5); + Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(composed.vars.get(1).baseName, "modelTwoProp"); + Assert.assertEquals(composed.vars.get(2).baseName, "simpleCompositionProp"); + Assert.assertEquals(composed.vars.get(3).baseName, "modelThreeProp"); + Assert.assertEquals(composed.vars.get(4).baseName, "compositionOfSimpleCompositionProp"); + Assert.assertNull(composed.parent); + } + + @Test(description = "handle simple inheritance") + public void simpleInheritanceTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 2); + Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(child.vars.get(1).baseName, "childOfSimpleParentProp"); + Assert.assertEquals(child.parent, "SimpleParent"); + } + + @Test(description = "handle multi level inheritance") + public void multiInheritanceTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); + Assert.assertEquals(child.parent, "ChildOfSimpleParent"); + } + + @Test(description = "copy properties in multi level inheritance if supportsInheritance is false") + public void noSupportsInheritanceTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 5); + Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(child.vars.get(1).baseName, "disc"); + Assert.assertEquals(child.vars.get(2).baseName, "simpleParentProp"); + Assert.assertEquals(child.vars.get(3).baseName, "childOfSimpleParentProp"); + Assert.assertEquals(child.vars.get(4).baseName, "childOfChildOfSimpleParentProp"); + Assert.assertEquals(child.parent, "ChildOfSimpleParent"); + } + + @Test(description = "don't copy interfaces properties if supportsMixins is true") + public void supportsMixinsTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + codegen.supportsMixins = true; + final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); + Assert.assertEquals(child.allVars.size(), 5); + Assert.assertEquals(child.allVars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(child.allVars.get(1).baseName, "disc"); + Assert.assertEquals(child.allVars.get(2).baseName, "simpleParentProp"); + Assert.assertEquals(child.allVars.get(3).baseName, "childOfSimpleParentProp"); + Assert.assertEquals(child.allVars.get(4).baseName, "childOfChildOfSimpleParentProp"); + + Assert.assertEquals(child.parent, "ChildOfSimpleParent"); + } + + @Test(description = "handle inheritance from composed model") + public void inheritanceOfComposedModelTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfComposedParent"); + CodegenModel child = codegen.fromModel("ChildOfComposedParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfComposedParentProp"); + Assert.assertEquals(child.parent, "ComposedParent"); + } + + @Test(description = "handle multi level inheritance from composed model") + public void multiInheritanceOfComposedModelTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfChildOfComposedParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfComposedParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfComposedParentProp"); + Assert.assertEquals(child.parent, "ChildOfComposedParent"); + } + + @Test(description = "use operation consumes and produces") public void localConsumesAndProducesTest() { final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index bfc25b8f5cc..f05c0e32700 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -163,6 +163,7 @@ public void testSkipOverwrite() throws Exception { final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json"); CodegenConfig codegenConfig = new JavaClientCodegen(); + codegenConfig.setLibrary("jersey1"); codegenConfig.setOutputDir(output.getAbsolutePath()); ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); 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 dfa4337e081..6b9c3a3c5b1 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 @@ -15,7 +15,7 @@ @SuppressWarnings("static-method") public class InlineModelResolverTest { @Test - public void resolveInlineModelTest() throws Exception { + public void resolveInlineModelTestWithoutTitle() throws Exception { Swagger swagger = new Swagger(); swagger.addDefinition("User", new ModelImpl() @@ -23,7 +23,6 @@ public void resolveInlineModelTest() throws Exception { .description("a common user") .property("name", new StringProperty()) .property("address", new ObjectProperty() - .title("title") ._default("default") .access("access") .readOnly(false) @@ -46,6 +45,143 @@ public void resolveInlineModelTest() throws Exception { assertNotNull(address.getProperties().get("street")); } + @Test + public void resolveInlineModelTestWithTitle() throws Exception { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property("address", new ObjectProperty() + .title("UserAddressTitle") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + new InlineModelResolver().flatten(swagger); + + ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + + assertNotNull(user); + assertTrue(user.getProperties().get("address") instanceof RefProperty); + + ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); + assertNotNull(address); + assertNotNull(address.getProperties().get("city")); + assertNotNull(address.getProperties().get("street")); + } + + @Test + public void resolveInlineModel2EqualInnerModels() throws Exception { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property("address", new ObjectProperty() + .title("UserAddressTitle") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + swagger.addDefinition("AnotherUser", new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property("lastName", new StringProperty()) + .property("address", new ObjectProperty() + .title("UserAddressTitle") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + new InlineModelResolver().flatten(swagger); + + ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + + assertNotNull(user); + assertTrue(user.getProperties().get("address") instanceof RefProperty); + + ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); + assertNotNull(address); + assertNotNull(address.getProperties().get("city")); + assertNotNull(address.getProperties().get("street")); + ModelImpl duplicateAddress = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle_0"); + assertNull(duplicateAddress); + } + + @Test + public void resolveInlineModel2DifferentInnerModelsWIthSameTitle() throws Exception { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property("address", new ObjectProperty() + .title("UserAddressTitle") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + swagger.addDefinition("AnotherUser", new ModelImpl() + .name("AnotherUser") + .description("a common user") + .property("name", new StringProperty()) + .property("lastName", new StringProperty()) + .property("address", new ObjectProperty() + .title("UserAddressTitle") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()) + .property("apartment", new StringProperty()))); + + new InlineModelResolver().flatten(swagger); + + ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + + assertNotNull(user); + assertTrue(user.getProperties().get("address") instanceof RefProperty); + + ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); + assertNotNull(address); + assertNotNull(address.getProperties().get("city")); + assertNotNull(address.getProperties().get("street")); + ModelImpl duplicateAddress = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle_1"); + assertNotNull(duplicateAddress); + assertNotNull(duplicateAddress.getProperties().get("city")); + assertNotNull(duplicateAddress.getProperties().get("street")); + assertNotNull(duplicateAddress.getProperties().get("apartment")); + } + + @Test public void testInlineResponseModel() throws Exception { Swagger swagger = new Swagger(); @@ -55,21 +191,24 @@ public void testInlineResponseModel() throws Exception { .response(200, new Response() .description("it works!") .schema(new ObjectProperty() - .property("name", new StringProperty()))))) + .property("name", new StringProperty()).vendorExtension("x-ext", "ext-prop"))))) .path("/foo/baz", new Path() .get(new Operation() .response(200, new Response() .vendorExtension("x-foo", "bar") .description("it works!") .schema(new ObjectProperty() - .property("name", new StringProperty()))))); + .property("name", new StringProperty()).vendorExtension("x-ext", "ext-prop"))))); new InlineModelResolver().flatten(swagger); Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); Response response = responses.get("200"); assertNotNull(response); - assertTrue(response.getSchema() instanceof RefProperty); + Property schema = response.getSchema(); + assertTrue(schema instanceof RefProperty); + assertEquals(1, schema.getVendorExtensions().size()); + assertEquals("ext-prop", schema.getVendorExtensions().get("x-ext")); ModelImpl model = (ModelImpl)swagger.getDefinitions().get("inline_response_200"); assertTrue(model.getProperties().size() == 1); @@ -112,12 +251,12 @@ public void testInlineResponseModelWithTitle() throws Exception { @Test - public void resolveInlineArrayModel() throws Exception { + public void resolveInlineArrayModelWithTitle() throws Exception { Swagger swagger = new Swagger(); swagger.addDefinition("User", new ArrayModel() .items(new ObjectProperty() - .title("title") + .title("InnerUserTitle") ._default("default") .access("access") .readOnly(false) @@ -132,10 +271,38 @@ public void resolveInlineArrayModel() throws Exception { Model model = swagger.getDefinitions().get("User"); assertTrue(model instanceof ArrayModel); - Model user = swagger.getDefinitions().get("User_inner"); + Model user = swagger.getDefinitions().get("InnerUserTitle"); assertNotNull(user); assertEquals("description", user.getDescription()); } + + @Test + public void resolveInlineArrayModelWithoutTitle() throws Exception { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ArrayModel() + .items(new ObjectProperty() + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + new InlineModelResolver().flatten(swagger); + + Model model = swagger.getDefinitions().get("User"); + assertTrue(model instanceof ArrayModel); + + Model user = swagger.getDefinitions().get("User_inner"); + assertNotNull(user); + assertEquals("description", user.getDescription()); + } + + + @Test public void resolveInlineBodyParameter() throws Exception { @@ -269,15 +436,17 @@ public void resolveInlineArrayBodyParameter() throws Exception { public void resolveInlineArrayResponse() throws Exception { Swagger swagger = new Swagger(); - swagger.path("/foo/baz", new Path() + ArrayProperty schema = new ArrayProperty() + .items(new ObjectProperty() + .property("name", new StringProperty()) + .vendorExtension("x-ext", "ext-items")) + .vendorExtension("x-ext", "ext-prop"); + swagger.path("/foo/baz", new Path() .get(new Operation() .response(200, new Response() .vendorExtension("x-foo", "bar") .description("it works!") - .schema(new ArrayProperty() - .items( - new ObjectProperty() - .property("name", new StringProperty())))))); + .schema(schema)))); new InlineModelResolver().flatten(swagger); @@ -291,6 +460,9 @@ public void resolveInlineArrayResponse() throws Exception { assertTrue(responseProperty instanceof ArrayProperty); ArrayProperty ap = (ArrayProperty) responseProperty; + assertEquals(1, ap.getVendorExtensions().size()); + assertEquals("ext-prop", ap.getVendorExtensions().get("x-ext")); + Property p = ap.getItems(); assertNotNull(p); @@ -299,6 +471,8 @@ public void resolveInlineArrayResponse() throws Exception { assertEquals(rp.getType(), "ref"); assertEquals(rp.get$ref(), "#/definitions/inline_response_200"); assertEquals(rp.getSimpleRef(), "inline_response_200"); + assertEquals(1, rp.getVendorExtensions().size()); + assertEquals("ext-items", rp.getVendorExtensions().get("x-ext")); Model inline = swagger.getDefinitions().get("inline_response_200"); assertNotNull(inline); @@ -358,6 +532,7 @@ public void testInlineMapResponse() throws Exception { MapProperty schema = new MapProperty(); schema.setAdditionalProperties(new StringProperty()); + schema.setVendorExtension("x-ext", "ext-prop"); swagger.path("/foo/baz", new Path() .get(new Operation() @@ -373,6 +548,8 @@ public void testInlineMapResponse() throws Exception { Property property = response.getSchema(); assertTrue(property instanceof MapProperty); assertTrue(swagger.getDefinitions().size() == 0); + assertEquals(1, property.getVendorExtensions().size()); + assertEquals("ext-prop", property.getVendorExtensions().get("x-ext")); } @Test @@ -382,6 +559,7 @@ public void testInlineMapResponseWithObjectProperty() throws Exception { MapProperty schema = new MapProperty(); schema.setAdditionalProperties(new ObjectProperty() .property("name", new StringProperty())); + schema.setVendorExtension("x-ext", "ext-prop"); swagger.path("/foo/baz", new Path() .get(new Operation() @@ -394,6 +572,8 @@ public void testInlineMapResponseWithObjectProperty() throws Exception { Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); Property property = response.getSchema(); assertTrue(property instanceof MapProperty); + assertEquals(1, property.getVendorExtensions().size()); + assertEquals("ext-prop", property.getVendorExtensions().get("x-ext")); assertTrue(swagger.getDefinitions().size() == 1); Model inline = swagger.getDefinitions().get("inline_response_200"); @@ -710,12 +890,11 @@ public void testArbitraryObjectModelInline() { } @Test - public void testArbitraryObjectModelWithArrayInline() { + public void testArbitraryObjectModelWithArrayInlineWithoutTitle() { Swagger swagger = new Swagger(); swagger.addDefinition("User", new ArrayModel() .items(new ObjectProperty() - .title("title") ._default("default") .access("access") .readOnly(false) @@ -739,4 +918,35 @@ public void testArbitraryObjectModelWithArrayInline() { ObjectProperty op = (ObjectProperty) inlineProp; assertNull(op.getProperties()); } + + @Test + public void testArbitraryObjectModelWithArrayInlineWithTitle() { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ArrayModel() + .items(new ObjectProperty() + .title("InnerUserTitle") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("arbitrary", new ObjectProperty()))); + + new InlineModelResolver().flatten(swagger); + + Model model = swagger.getDefinitions().get("User"); + assertTrue(model instanceof ArrayModel); + ArrayModel am = (ArrayModel) model; + Property inner = am.getItems(); + assertTrue(inner instanceof RefProperty); + + ModelImpl userInner = (ModelImpl)swagger.getDefinitions().get("InnerUserTitle"); + assertNotNull(userInner); + Property inlineProp = userInner.getProperties().get("arbitrary"); + assertTrue(inlineProp instanceof ObjectProperty); + ObjectProperty op = (ObjectProperty) inlineProp; + assertNull(op.getProperties()); + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java index 7ad1ff07e2b..4acf7d5aaa9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AkkaScalaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(AkkaScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java index 538614436f4..b94ec49f361 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -46,6 +46,8 @@ protected void setExpectations() { times = 1; clientCodegen.setLibrary(AndroidClientOptionsProvider.LIBRARY_VALUE); times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(AndroidClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java index 8ea0280434a..12f4f19e379 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AsyncScalaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(AsyncScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index 71975fcee66..f53ac5e0626 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -48,6 +48,8 @@ protected void setExpectations() { times = 1; clientCodegen.setOptionalEmitDefaultValue(true); times = 1; + clientCodegen.setGeneratePropertyChanged(true); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java new file mode 100644 index 00000000000..61da755f146 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java @@ -0,0 +1,35 @@ +package io.swagger.codegen.java; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.languages.AbstractJavaCodegen; + +public class AbstractJavaCodegenTest { + + private final AbstractJavaCodegen fakeJavaCodegen = new AbstractJavaCodegen() { + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + }; + + @Test + public void toEnumVarNameShouldNotShortenUnderScore() throws Exception { + Assert.assertEquals("UNDERSCORE", fakeJavaCodegen.toEnumVarName("_", "String")); + Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("__", "String")); + Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("_,.", "String")); + } + +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index aea42d72401..73dabd98cf2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -56,6 +56,8 @@ protected void setExpectations() { times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaOptionsProvider.USE_BEANVALIDATION)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java index dcd87b4d700..a4cb27db756 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java @@ -13,10 +13,14 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + public class JavaInheritanceTest { @SuppressWarnings("static-method") - @Test(description = "convert a composed model") + @Test(description = "convert a composed model with parent") public void javaInheritanceTest() { final Model model = new ComposedModel().parent(new RefModel("Base")) .child(new ModelImpl().additionalProperties(new StringProperty())); @@ -29,4 +33,26 @@ public void javaInheritanceTest() { Assert.assertEquals(cm.parent, "Base"); Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); } + + @SuppressWarnings("static-method") + @Test(description = "convert a composed model with discriminator") + public void javaInheritanceWithDiscriminatorTest() { + ModelImpl base = new ModelImpl(); + base.setDiscriminator("disc"); + + final Model model = new ComposedModel() + .interfaces(Arrays.asList(new RefModel("Base"))) + .child(new ModelImpl().additionalProperties(new StringProperty())); + + final Map allDefinitions = new HashMap(); + allDefinitions.put("Base", base); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java index 94285e46888..592a9e2ae58 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java @@ -51,7 +51,7 @@ public void javascriptInheritanceTest() { Assert.assertEquals(cm.vars.size(), 1); Assert.assertEquals(cm.vars.get(0).name, "childProp"); Assert.assertEquals(cm.allVars.size(), 4); - String[] allVars = {"baseProp", "intf1Prop", "intf2Prop", "childProp"}; + String[] allVars = {"intf1Prop", "intf2Prop", "baseProp", "childProp"}; for (int i = 0; i < allVars.length; i++) { Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); } @@ -91,7 +91,7 @@ public void javascriptNoInheritanceTest() { Assert.assertEquals(cm.imports, Sets.newHashSet("Base", "Interface1", "Interface2")); Assert.assertEquals(cm.vars.size(), 4); Assert.assertEquals(cm.allVars.size(), 4); - String[] allVars = {"baseProp", "intf1Prop", "intf2Prop", "childProp"}; + String[] allVars = {"intf1Prop", "intf2Prop", "baseProp", "childProp"}; for (int i = 0; i < allVars.length; i++) { Assert.assertEquals(cm.vars.get(i).name, allVars[i]); Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java index 5e2306d73fb..e87c78e78ba 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java @@ -11,6 +11,8 @@ import io.swagger.models.RefModel; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; import org.testng.Assert; import org.testng.annotations.Test; @@ -92,4 +94,61 @@ public void overrideEnumTest() { Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum"); Assert.assertTrue(enumVar.isEnum); } + + @Test(description = "test enum array model") + public void enumArrayMdoelTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final Model definition = model.getDefinitions().get("EnumArrays"); + + Property property = definition.getProperties().get("array_enum"); + CodegenProperty prope = codegen.fromProperty("array_enum", property); + codegen.updateCodegenPropertyEnum(prope); + Assert.assertEquals(prope.datatypeWithEnum, "[ArrayEnumEnum]"); + Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); + Assert.assertTrue(prope.isEnum); + Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); + + HashMap fish= new HashMap(); + fish.put("name", "fish"); + fish.put("value", "\"fish\""); + HashMap crab= new HashMap(); + crab.put("name", "crab"); + crab.put("value", "\"crab\""); + Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); + + // assert inner items + Assert.assertEquals(prope.datatypeWithEnum, "[ArrayEnumEnum]"); + Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); + Assert.assertTrue(prope.items.isEnum); + Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); + Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); + + } + + @Test(description = "test enum model for values (numeric, string, etc)") + public void enumMdoelValueTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final Model definition = model.getDefinitions().get("Enum_Test"); + + Property property = definition.getProperties().get("enum_integer"); + CodegenProperty prope = codegen.fromProperty("enum_integer", property); + codegen.updateCodegenPropertyEnum(prope); + Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); + Assert.assertEquals(prope.enumName, "EnumIntegerEnum"); + Assert.assertTrue(prope.isEnum); + Assert.assertNull(prope.isContainer); + Assert.assertNull(prope.items); + Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); + + HashMap one = new HashMap(); + one.put("name", "1"); + one.put("value", "1"); + HashMap minusOne = new HashMap(); + minusOne.put("name", "-1"); + minusOne.put("value", "-1"); + Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); + + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java index bb7afb942b7..c396ec26f1c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java @@ -52,10 +52,10 @@ public void simpleModelTest() { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.getter, "getId"); Assert.assertEquals(property1.setter, "setId"); - Assert.assertEquals(property1.datatype, "Integer"); + Assert.assertEquals(property1.datatype, "Number"); Assert.assertEquals(property1.name, "id"); Assert.assertEquals(property1.defaultValue, null); - Assert.assertEquals(property1.baseType, "Integer"); + Assert.assertEquals(property1.baseType, "Number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); Assert.assertTrue(property1.isNotContainer); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java deleted file mode 100644 index acede31f736..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.swagger.codegen.languages; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SwiftCodegenTest { - - SwiftCodegen swiftCodegen = new SwiftCodegen(); - - @Test - public void shouldNotBreakCorrectName() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("EntryName"), "EntryName"); - } - - @Test - public void testSingleWordAllCaps() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("VALUE"), "Value"); - } - - @Test - public void testSingleWordLowercase() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("value"), "Value"); - } - - @Test - public void testCapitalsWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY_NAME"), "EntryName"); - } - - @Test - public void testCapitalsWithDash() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY-NAME"), "EntryName"); - } - - @Test - public void testCapitalsWithSpace() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY NAME"), "EntryName"); - } - - @Test - public void testLowercaseWithUnderscore() throws Exception { - Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); - } - -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java index dcb89d263cc..434e318f593 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java @@ -28,6 +28,24 @@ protected void setExpectations() { new Expectations(clientCodegen) {{ clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(LumenServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setParameterNamingConvention(LumenServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); + clientCodegen.setModelPackage(LumenServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(LumenServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + times = 1; + clientCodegen.setInvokerPackage(LumenServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setPackagePath(LumenServerOptionsProvider.PACKAGE_PATH_VALUE); + times = 1; + clientCodegen.setSrcBasePath(LumenServerOptionsProvider.SRC_BASE_PATH_VALUE); + times = 1; + clientCodegen.setGitUserId(LumenServerOptionsProvider.GIT_USER_ID_VALUE); + times = 1; + clientCodegen.setGitRepoId(LumenServerOptionsProvider.GIT_REPO_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(LumenServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index 76e5ced012f..c2d0fd0f7af 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -224,7 +224,7 @@ public void complexMapPropertyTest() { final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.complexType, "SWGChildren"); - Assert.assertEquals(property1.datatype, "NSDictionary*"); + Assert.assertEquals(property1.datatype, "NSDictionary*"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java index e26968500d7..c9fd8bca97a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class AkkaScalaClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index 82ffa437f2a..79e61844c8b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -19,6 +19,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; public static final String LIBRARY_VALUE = "httpclient"; + public static final String SERIALIZABLE_MODEL_VALUE = "false"; @Override public String getLanguage() { @@ -39,6 +40,7 @@ public Map createOptions() { .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) + .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java index be21a20efe4..aa09c1e4aec 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class AsyncScalaClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 5f43f5cf155..a438a31e2b7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -33,6 +33,8 @@ public Map createOptions() { .put(CodegenConstants.OPTIONAL_PROJECT_GUID, PACKAGE_GUID_VALUE) .put(CodegenConstants.DOTNET_FRAMEWORK, "4.x") .put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, "true") + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.GENERATE_PROPERTY_CHANGED, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java index 304d8acf457..af1613e8051 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java @@ -23,6 +23,7 @@ public Map createOptions() { return builder .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java index 53cfe826d36..88255633518 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java @@ -16,6 +16,8 @@ public Map createOptions() { Map options = new HashMap(super.createOptions()); options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE); options.put(JavaClientCodegen.USE_RX_JAVA, "false"); + options.put(JavaClientCodegen.PARCELABLE_MODEL, "false"); + options.put(JavaClientCodegen.USE_BEANVALIDATION, "false"); return options; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 468eb5c972f..b8412e79e92 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -19,6 +19,7 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String FULL_JAVA_UTIL_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String USE_BEANVALIDATION = "false"; private ImmutableMap options; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java index b445fc1c528..5b75f59b356 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java @@ -58,6 +58,7 @@ public JavaScriptOptionsProvider() { .put(JavascriptClientCodegen.USE_INHERITANCE, USE_INHERITANCE_VALUE) .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaUndertowServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaUndertowServerOptionsProvider.java new file mode 100644 index 00000000000..9a1ab264fd3 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaUndertowServerOptionsProvider.java @@ -0,0 +1,16 @@ +package io.swagger.codegen.options; + +/** + * Created by steve on 18/09/16. + */ +public class JavaUndertowServerOptionsProvider extends JavaOptionsProvider { + @Override + public String getLanguage() { + return "undertow"; + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java index 3bc5a3df22d..baf4cfb8537 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java @@ -20,6 +20,7 @@ public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java index 1ffc290ee46..6edc611b59e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java @@ -1,14 +1,24 @@ package io.swagger.codegen.options; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.AbstractPhpCodegen; import com.google.common.collect.ImmutableMap; import java.util.Map; public class LumenServerOptionsProvider implements OptionsProvider { + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; + public static final String INVOKER_PACKAGE_VALUE = "lumen"; + public static final String PACKAGE_PATH_VALUE = "php"; + public static final String SRC_BASE_PATH_VALUE = "libPhp"; + public static final String GIT_USER_ID_VALUE = "gitSwaggerPhp"; + public static final String GIT_REPO_ID_VALUE = "git-swagger-php"; + public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; @Override public String getLanguage() { @@ -18,8 +28,17 @@ public String getLanguage() { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) + .put(AbstractPhpCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) + .put(AbstractPhpCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GIT_USER_ID, GIT_USER_ID_VALUE) + .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java index 4df5c5e1db6..667fc1c9027 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java @@ -31,6 +31,7 @@ public Map createOptions() { .put(ObjcClientCodegen.AUTHOR_EMAIL, AUTHOR_EMAIL_VALUE) .put(ObjcClientCodegen.GIT_REPO_URL, GIT_REPO_URL_VALUE) .put(ObjcClientCodegen.CORE_DATA, CORE_DATA_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java index 8aa37f12fd0..26cdacc98b2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java @@ -43,6 +43,7 @@ public Map createOptions() { .put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java index ec62e3f2b7c..ccdb38d7bab 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java @@ -21,6 +21,7 @@ public Map createOptions() { return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index 64e388d38ef..34a36534a31 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -14,6 +14,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String GEM_LICENSE_VALUE = "MIT"; + public static final String GEM_REQUIRED_RUBY_VERSION_VALUE = ">= 1.9"; public static final String GEM_HOMEPAGE_VALUE = "homepage"; public static final String GEM_SUMMARY_VALUE = "summary"; public static final String GEM_DESCRIPTION_VALUE = "description"; @@ -32,6 +33,7 @@ public Map createOptions() { .put(RubyClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) .put(RubyClientCodegen.GEM_VERSION, GEM_VERSION_VALUE) .put(RubyClientCodegen.GEM_LICENSE, GEM_LICENSE_VALUE) + .put(RubyClientCodegen.GEM_REQUIRED_RUBY_VERSION, GEM_REQUIRED_RUBY_VERSION_VALUE) .put(RubyClientCodegen.GEM_DESCRIPTION, GEM_DESCRIPTION_VALUE) .put(RubyClientCodegen.GEM_HOMEPAGE, GEM_HOMEPAGE_VALUE) .put(RubyClientCodegen.GEM_SUMMARY, GEM_SUMMARY_VALUE) @@ -39,6 +41,7 @@ public Map createOptions() { .put(RubyClientCodegen.GEM_AUTHOR_EMAIL, GEM_AUTHOR_EMAIL_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java index 867482f145b..f8a22c031ba 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java @@ -7,10 +7,12 @@ import java.util.Map; public class ScalaClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; @Override public String getLanguage() { @@ -24,6 +26,8 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java index a0fef2f4858..e36ed80bbd5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class ScalatraServerOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index 3d56410f937..34041370df9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -1,41 +1,43 @@ -package io.swagger.codegen.options; - -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.SpringCodegen; - -import java.util.HashMap; -import java.util.Map; - -public class SpringOptionsProvider extends JavaOptionsProvider { - public static final String CONFIG_PACKAGE_VALUE = "configPackage"; - public static final String BASE_PACKAGE_VALUE = "basePackage"; - public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class - public static final String INTERFACE_ONLY = "true"; - public static final String SINGLE_CONTENT_TYPES = "true"; - public static final String JAVA_8 = "true"; - public static final String ASYNC = "true"; - - @Override - public String getLanguage() { - return "spring"; - } - - @Override - public Map createOptions() { - Map options = new HashMap(super.createOptions()); - options.put(SpringCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); - options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); - options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); - options.put(SpringCodegen.INTERFACE_ONLY, INTERFACE_ONLY); - options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); - options.put(SpringCodegen.JAVA_8, JAVA_8); - options.put(SpringCodegen.ASYNC, ASYNC); - - return options; - } - - @Override - public boolean isServer() { - return true; - } -} +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.SpringCodegen; + +import java.util.HashMap; +import java.util.Map; + +public class SpringOptionsProvider extends JavaOptionsProvider { + public static final String TITLE = "swagger"; + public static final String CONFIG_PACKAGE_VALUE = "configPackage"; + public static final String BASE_PACKAGE_VALUE = "basePackage"; + public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class + public static final String INTERFACE_ONLY = "true"; + public static final String SINGLE_CONTENT_TYPES = "true"; + public static final String JAVA_8 = "true"; + public static final String ASYNC = "true"; + + @Override + public String getLanguage() { + return "spring"; + } + + @Override + public Map createOptions() { + Map options = new HashMap(super.createOptions()); + options.put(SpringCodegen.TITLE, TITLE); + options.put(SpringCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); + options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); + options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); + options.put(SpringCodegen.INTERFACE_ONLY, INTERFACE_ONLY); + options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); + options.put(SpringCodegen.JAVA_8, JAVA_8); + options.put(SpringCodegen.ASYNC, ASYNC); + + return options; + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java index ff5daa86797..3d73e681c8c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java @@ -20,6 +20,7 @@ public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put("outputFile", "swagger.yaml") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java index 3794cb9a76f..b79ecfb351d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java @@ -52,6 +52,7 @@ public Map createOptions() { .put(SwiftCodegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE) .put(SwiftCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) .put(SwiftCodegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java index ef6d6984895..035daa9bf33 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -7,12 +7,20 @@ import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; +import io.swagger.models.properties.Property; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.DateTimeProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import com.google.common.collect.Sets; import org.testng.Assert; @@ -268,4 +276,65 @@ public void modelNameTest(String name, String expectedName) { Assert.assertEquals(cm.name, name); Assert.assertEquals(cm.classname, expectedName); } + + @Test(description = "test enum array model") + public void enumArrayMdoelTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final DefaultCodegen codegen = new PhpClientCodegen(); + final Model definition = model.getDefinitions().get("EnumArrays"); + + Property property = definition.getProperties().get("array_enum"); + CodegenProperty prope = codegen.fromProperty("array_enum", property); + codegen.updateCodegenPropertyEnum(prope); + Assert.assertEquals(prope.datatypeWithEnum, "ARRAY_ENUM[]"); + Assert.assertEquals(prope.enumName, "ARRAY_ENUM"); + Assert.assertTrue(prope.isEnum); + Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); + + HashMap fish= new HashMap(); + fish.put("name", "FISH"); + fish.put("value", "\'fish\'"); + HashMap crab= new HashMap(); + crab.put("name", "CRAB"); + crab.put("value", "\'crab\'"); + Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); + + // assert inner items + Assert.assertEquals(prope.datatypeWithEnum, "ARRAY_ENUM[]"); + Assert.assertEquals(prope.enumName, "ARRAY_ENUM"); + Assert.assertTrue(prope.items.isEnum); + Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); + Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); + + } + + @Test(description = "test enum model for values (numeric, string, etc)") + public void enumMdoelValueTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final DefaultCodegen codegen = new PhpClientCodegen(); + final Model definition = model.getDefinitions().get("Enum_Test"); + + Property property = definition.getProperties().get("enum_integer"); + CodegenProperty prope = codegen.fromProperty("enum_integer", property); + codegen.updateCodegenPropertyEnum(prope); + Assert.assertEquals(prope.datatypeWithEnum, "ENUM_INTEGER"); + Assert.assertEquals(prope.enumName, "ENUM_INTEGER"); + Assert.assertTrue(prope.isEnum); + Assert.assertNull(prope.isContainer); + Assert.assertNull(prope.items); + Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); + + HashMap one = new HashMap(); + one.put("name", "1"); + one.put("value", "1"); + HashMap minusOne = new HashMap(); + minusOne.put("name", "MINUS_1"); + minusOne.put("value", "-1"); + Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); + + } + + + + } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java index f61367e8220..9bf7eea4c94 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -34,6 +34,8 @@ protected void setExpectations() { times = 1; clientCodegen.setGemLicense(RubyClientOptionsProvider.GEM_LICENSE_VALUE); times = 1; + clientCodegen.setGemRequiredRubyVersion(RubyClientOptionsProvider.GEM_REQUIRED_RUBY_VERSION_VALUE); + times = 1; clientCodegen.setGemHomepage(RubyClientOptionsProvider.GEM_HOMEPAGE_VALUE); times = 1; clientCodegen.setGemDescription(RubyClientOptionsProvider.GEM_DESCRIPTION_VALUE); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java index fe0b3b3b544..d03cfee7ee7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java @@ -32,6 +32,10 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setModelPropertyNaming(ScalaClientOptionsProvider.MODEL_PROPERTY_NAMING); + times = 1; + clientCodegen.setSourceFolder(ScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java index 70c3dd30987..53ff0ce48e5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(ScalatraServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index 3693ab6c550..da3513b34cc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -1,68 +1,70 @@ -package io.swagger.codegen.spring; - -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.java.JavaClientOptionsTest; -import io.swagger.codegen.languages.SpringCodegen; -import io.swagger.codegen.options.SpringOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class SpringOptionsTest extends JavaClientOptionsTest { - - @Tested - private SpringCodegen clientCodegen; - - public SpringOptionsTest() { - super(new SpringOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); - times = 1; - clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); - times = 1; - clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); - times = 1; - clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); - times = 1; - clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); - times = 1; - clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); - times = 1; - - }}; - } -} +package io.swagger.codegen.spring; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.SpringCodegen; +import io.swagger.codegen.options.SpringOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SpringOptionsTest extends JavaClientOptionsTest { + + @Tested + private SpringCodegen clientCodegen; + + public SpringOptionsTest() { + super(new SpringOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setTitle(SpringOptionsProvider.TITLE); + times = 1; + clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); + times = 1; + clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); + times = 1; + clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); + times = 1; + clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); + times = 1; + clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); + times = 1; + clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); + times = 1; + + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java new file mode 100644 index 00000000000..62a6fb58482 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java @@ -0,0 +1,97 @@ +package io.swagger.codegen.swift; + +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.InlineModelResolver; +import io.swagger.codegen.languages.SwiftCodegen; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SwiftCodegenTest { + + SwiftCodegen swiftCodegen = new SwiftCodegen(); + + @Test + public void shouldNotBreakCorrectName() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("EntryName"), "EntryName"); + } + + @Test + public void testSingleWordAllCaps() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("VALUE"), "Value"); + } + + @Test + public void testSingleWordLowercase() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("value"), "Value"); + } + + @Test + public void testCapitalsWithUnderscore() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY_NAME"), "EntryName"); + } + + @Test + public void testCapitalsWithDash() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY-NAME"), "EntryName"); + } + + @Test + public void testCapitalsWithSpace() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY NAME"), "EntryName"); + } + + @Test + public void testLowercaseWithUnderscore() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); + } + + @Test + public void testSlash() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("application/x-tar"), "ApplicationXTar"); + } + + @Test(description = "returns NSData when response format is binary") + public void binaryDataTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final DefaultCodegen codegen = new SwiftCodegen(); + final String path = "/tests/binaryResponse"; + final Operation p = model.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "NSData"); + Assert.assertEquals(op.bodyParam.dataType, "NSData"); + Assert.assertTrue(op.bodyParam.isBinary); + Assert.assertTrue(op.responses.get(0).isBinary); + } + + @Test + public void testDefaultPodAuthors() throws Exception { + // Given + + // When + swiftCodegen.processOpts(); + + // Then + final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); + Assert.assertEquals(podAuthors, SwiftCodegen.DEFAULT_POD_AUTHORS); + } + + @Test + public void testPodAuthors() throws Exception { + // Given + final String swaggerDevs = "Swagger Devs"; + swiftCodegen.additionalProperties().put(SwiftCodegen.POD_AUTHORS, swaggerDevs); + + // When + swiftCodegen.processOpts(); + + // Then + final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); + Assert.assertEquals(podAuthors, swaggerDevs); + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java new file mode 100644 index 00000000000..c3d2d829c9c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java @@ -0,0 +1,99 @@ +package io.swagger.codegen.swift; + +import io.swagger.codegen.*; +import io.swagger.codegen.languages.SwiftCodegen; +import io.swagger.models.*; +import io.swagger.models.properties.*; + +import org.testng.Assert; +import org.testng.annotations.Test; + +@SuppressWarnings("static-method") +public class SwiftModelTest { + + @Test(description = "convert a simple java model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .property("binary", new BinaryProperty()) + .property("byte", new ByteArrayProperty()) + .property("uuid", new UUIDProperty()) + .required("id") + .required("name") + .discriminator("test"); + final DefaultCodegen codegen = new SwiftCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 6); + Assert.assertEquals(cm.discriminator,"test"); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "Int64"); + Assert.assertEquals(property1.name, "id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "Int64"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.datatype, "NSDate"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "NSDate"); + Assert.assertTrue(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "binary"); + Assert.assertEquals(property4.datatype, "NSData"); + Assert.assertEquals(property4.name, "binary"); + Assert.assertNull(property4.defaultValue); + Assert.assertEquals(property4.baseType, "NSData"); + Assert.assertTrue(property4.hasMore); + Assert.assertNull(property4.required); + Assert.assertTrue(property4.isNotContainer); + + final CodegenProperty property5 = cm.vars.get(4); + Assert.assertEquals(property5.baseName, "byte"); + Assert.assertEquals(property5.datatype, "NSData"); + Assert.assertEquals(property5.name, "byte"); + Assert.assertNull(property5.defaultValue); + Assert.assertEquals(property5.baseType, "NSData"); + Assert.assertTrue(property5.hasMore); + Assert.assertNull(property5.required); + Assert.assertTrue(property5.isNotContainer); + + final CodegenProperty property6 = cm.vars.get(5); + Assert.assertEquals(property6.baseName, "uuid"); + Assert.assertEquals(property6.datatype, "NSUUID"); + Assert.assertEquals(property6.name, "uuid"); + Assert.assertNull(property6.defaultValue); + Assert.assertEquals(property6.baseType, "NSUUID"); + Assert.assertNull(property6.hasMore); + Assert.assertNull(property6.required); + Assert.assertTrue(property6.isNotContainer); + } + +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java index f810e20eb0a..aca2beb2dc5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java @@ -113,12 +113,12 @@ public static void assertFilesAreEqual(final Path expected, final Path actual) { if(!deltas.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("files diff:\n"); - stringBuilder.append("\tfile: '" + expected.toAbsolutePath().toString() + "' \n"); - stringBuilder.append("\tfile: '" + actual.toAbsolutePath().toString() + "' \n"); + stringBuilder.append("\tfile: '").append(expected.toAbsolutePath().toString()).append("' \n"); + stringBuilder.append("\tfile: '").append(actual.toAbsolutePath().toString()).append("' \n"); stringBuilder.append("\tdiffs:\n"); for (Delta delta: deltas) { - stringBuilder.append(delta.toString() + "\n"); + stringBuilder.append(delta.toString()).append("\n"); } fail(stringBuilder.toString()); 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 d1b0a4be233..f6eb8cb2b63 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 @@ -12,11 +12,17 @@ import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; +import io.swagger.models.properties.Property; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.DateTimeProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; + +import java.util.HashMap; +import java.util.Arrays; @SuppressWarnings("static-method") public class TypeScriptFetchModelTest { @@ -180,4 +186,69 @@ public void mapModelTest() { Assert.assertEquals(cm.imports.size(), 1); Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); } + + @Test(description = "test enum array model") + public void enumArrayMdoelTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final Model definition = model.getDefinitions().get("EnumArrays"); + + Property property = definition.getProperties().get("array_enum"); + CodegenProperty prope = codegen.fromProperty("array_enum", property); + codegen.updateCodegenPropertyEnum(prope); + Assert.assertEquals(prope.datatypeWithEnum, "Array"); + Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); + Assert.assertTrue(prope.isEnum); + Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); + + HashMap fish= new HashMap(); + fish.put("name", "Fish"); + fish.put("value", "'fish'"); + HashMap crab= new HashMap(); + crab.put("name", "Crab"); + crab.put("value", "'crab'"); + Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); + + // assert inner items + Assert.assertEquals(prope.datatypeWithEnum, "Array"); + Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); + Assert.assertTrue(prope.items.isEnum); + Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); + Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); + + //IMPORTANT: these are not final enum values, which may be further updated + //by postProcessModels + + } + + @Test(description = "test enum model for values (numeric, string, etc)") + public void enumMdoelValueTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final Model definition = model.getDefinitions().get("Enum_Test"); + + Property property = definition.getProperties().get("enum_integer"); + CodegenProperty prope = codegen.fromProperty("enum_integer", property); + codegen.updateCodegenPropertyEnum(prope); + Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); + Assert.assertEquals(prope.enumName, "EnumIntegerEnum"); + Assert.assertTrue(prope.isEnum); + Assert.assertNull(prope.isContainer); + Assert.assertNull(prope.items); + Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); + + HashMap one = new HashMap(); + one.put("name", "NUMBER_1"); + one.put("value", "1"); + HashMap minusOne = new HashMap(); + minusOne.put("name", "NUMBER_MINUS_1"); + minusOne.put("value", "-1"); + Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); + + //IMPORTANT: these are not final enum values, which may be further updated + //by postProcessModels + + } + + } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java index 8b23105f28c..db3121c1dc0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java @@ -17,12 +17,12 @@ protected CodegenConfig getCodegenConfig() { @Override protected Map configProperties() { - Map propeties = new HashMap<>(); - propeties.put("npmName", "additionalPropertiesTest"); - propeties.put("npmVersion", "1.0.2"); - propeties.put("snapshot", "false"); + Map properties = new HashMap<>(); + properties.put("npmName", "additionalPropertiesTest"); + properties.put("npmVersion", "1.0.2"); + properties.put("snapshot", "false"); - return propeties; + return properties; } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java index b9a8868a6b8..e60f06ca57d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java @@ -17,12 +17,12 @@ protected CodegenConfig getCodegenConfig() { @Override protected Map configProperties() { - Map propeties = new HashMap<>(); - propeties.put("npmName", "arrayAndAnyTest"); - propeties.put("npmVersion", "1.0.2"); - propeties.put("snapshot", "false"); + Map properties = new HashMap<>(); + properties.put("npmName", "arrayAndAnyTest"); + properties.put("npmVersion", "1.0.2"); + properties.put("snapshot", "false"); - return propeties; + return properties; } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java index 22bac4ea316..5bf54ceee85 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java @@ -17,13 +17,13 @@ protected CodegenConfig getCodegenConfig() { @Override protected Map configProperties() { - Map propeties = new HashMap<>(); - propeties.put("npmName", "node-es6-test"); - propeties.put("npmVersion", "1.0.3"); - propeties.put("snapshot", "false"); - propeties.put("supportsES6", "false"); + Map properties = new HashMap<>(); + properties.put("npmName", "node-es6-test"); + properties.put("npmVersion", "1.0.3"); + properties.put("snapshot", "false"); + properties.put("supportsES6", "false"); - return propeties; + return properties; } @Override diff --git a/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet index 4a8439a4424..9ee8ba2b8e4 100644 --- a/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet +++ b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet @@ -246,7 +246,7 @@ { "method": "GET", "summary": "Finds Pets by status", - "notes": "Multiple status values can be provided with comma seperated strings", + "notes": "Multiple status values can be provided with comma separated strings", "type": "array", "items": { "$ref": "Pet" @@ -283,7 +283,7 @@ { "method": "GET", "summary": "Finds Pets by tags", - "notes": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "notes": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "type": "array", "items": { "$ref": "Pet" diff --git a/modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml b/modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml new file mode 100644 index 00000000000..2636d4e7aa9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml @@ -0,0 +1,104 @@ +swagger: '2.0' +info: + version: 0.0.0 + title: Simple API +paths: + /: + get: + responses: + 200: + description: OK + +definitions: + + ModelOne: + type: object + properties: + modelOneProp: + type: string + + ModelTwo: + type: object + properties: + modelTwoProp: + type: string + + ModelThree: + type: object + properties: + modelThreeProp: + type: string + + SimpleComposition: + allOf: + - $ref: '#/definitions/ModelOne' + - $ref: '#/definitions/ModelTwo' + - type: object + properties: + simpleCompositionProp: + type: string + + CompositionOfSimpleComposition: + allOf: + - $ref: '#/definitions/SimpleComposition' + - $ref: '#/definitions/ModelThree' + - type: object + properties: + compositionOfSimpleCompositionProp: + type: string + + SimpleParent: + type: object + discriminator: disc + properties: + disc: + type: string + simpleParentProp: + type: string + required: [disc] + + ChildOfSimpleParent: + allOf: + - $ref: '#/definitions/ModelOne' + - $ref: '#/definitions/SimpleParent' + - type: object + properties: + childOfSimpleParentProp: + type: string + + ChildOfChildOfSimpleParent: + allOf: + - $ref: '#/definitions/ChildOfSimpleParent' + - type: object + properties: + childOfChildOfSimpleParentProp: + type: string + + ComposedParent: + allOf: + - $ref: '#/definitions/ModelOne' + - $ref: '#/definitions/ModelTwo' + - type: object + discriminator: disc + properties: + disc: + type: string + composedParentProp: + type: string + required: [disc] + + ChildOfComposedParent: + allOf: + - $ref: '#/definitions/ComposedParent' + - type: object + properties: + childOfComposedParentProp: + type: string + + ChildOfChildOfComposedParent: + allOf: + - $ref: '#/definitions/ChildOfComposedParent' + - type: object + properties: + childOfChildOfComposedParentProp: + type: string \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json index 36fa87664ae..cc302bbf5a7 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json +++ b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json @@ -113,7 +113,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -163,7 +163,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json b/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json index 7422817fea7..58577dd2f52 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json @@ -113,7 +113,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -163,7 +163,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml index 38da7ff44d6..16bce94ac7d 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml @@ -1,68 +1,68 @@ 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: \" \\ */ ' \" =end" - version: 1.0.0 */ ' " =end - title: Swagger Petstore */ ' " =end - termsOfService: http://swagger.io/terms/ */ ' " =end + 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 -- \r\n \n \r" + version: 1.0.0 */ ' " =end -- \r\n \n \r + title: Swagger Petstore */ ' " =end -- \r\n \n \r + termsOfService: http://swagger.io/terms/ */ ' " =end -- \r\n \n \r contact: - email: apiteam@swagger.io */ ' " =end + email: apiteam@swagger.io */ ' " =end -- \r\n \n \r license: - name: Apache 2.0 */ ' " =end - url: http://www.apache.org/licenses/LICENSE-2.0.html */ ' " =end -host: petstore.swagger.io */ ' " =end -basePath: /v2 */ ' " =end + name: Apache 2.0 */ ' " =end -- \r\n \n \r + url: http://www.apache.org/licenses/LICENSE-2.0.html */ ' " =end -- \r\n \n \r +host: petstore.swagger.io */ ' " =end -- \r\n \n \r +basePath: /v2 */ ' " =end -- \r\n \n \r tags: - name: fake - description: Everything about your Pets */ ' " =end + description: Everything about your Pets */ ' " =end -- \r\n \n \r externalDocs: - description: Find out more */ ' " = end + description: Find out more */ ' " =end -- \r\n \n \r url: 'http://swagger.io' schemes: - - http */ end ' " + - http */ ' " =end -- \r\n \n \r paths: /fake: put: tags: - fake - summary: To test code injection */ ' " =end - descriptions: To test code injection */ ' " =end - operationId: testCodeInject */ ' " =end + summary: To test code injection */ ' " =end -- \r\n \n \r + descriptions: To test code injection */ ' " =end -- \r\n \n \r + operationId: testCodeInject */ ' " =end -- \r\n \n \r consumes: - application/json - - "*/ ' \" =end" + - "*/ ' \" =end -- \r\n \n \r" produces: - application/json - - "*/ ' \" =end" + - "*/ ' \" =end -- \r\n \n \r" parameters: - - name: test code inject */ ' " =end + - name: test code inject */ ' " =end -- \r\n \n \r type: string in: formData - description: To test code injection */ ' " =end + description: To test code injection */ ' " =end -- \r\n \n \r responses: '400': - description: To test code injection */ ' " =end + description: To test code injection */ ' " =end -- \r\n \n \r securityDefinitions: petstore_auth: type: oauth2 authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' flow: implicit scopes: - 'write:pets': modify pets in your account */ ' " =end - 'read:pets': read your pets */ ' " =end + 'write:pets': modify pets in your account */ ' " =end -- \r\n \n \r + 'read:pets': read your pets */ ' " =end -- \r\n \n \r api_key: type: apiKey - name: api_key */ ' " =end + name: api_key */ ' " =end -- \r\n \n \r in: header definitions: Return: - description: Model for testing reserved words */ ' " =end + description: Model for testing reserved words */ ' " =end -- \r\n \n \r properties: return: - description: property description */ ' " =end + description: property description */ ' " =end -- \r\n \n \r type: integer format: int32 xml: name: Return externalDocs: - description: Find out more about Swagger */ ' " =end + description: Find out more about Swagger */ ' " =end -- \r\n \n \r url: 'http://swagger.io' diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index d3d8287d915..c42dc774a22 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -561,18 +561,50 @@ paths: description: User not found /fake: + patch: + tags: + - fake + summary: To test "client" model + descriptions: 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' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Client' get: tags: - fake - summary: To test enum query parameters - descriptions: To test enum query parameters - operationId: testEnumQueryParameters + summary: To test enum parameters + descriptions: To test enum parameters + operationId: testEnumParameters consumes: - application/json produces: - application/json parameters: - - name: enum_query_string + - name: enum_form_string_array + type: array + items: + type: string + default: '$' + enum: + - '>' + - '$' + in: formData + description: Form parameter enum test (string array) + - name: enum_form_string type: string default: '-efg' enum: @@ -580,6 +612,44 @@ paths: - '-efg' - (xyz) in: formData + description: Form parameter enum test (string) + - name: enum_header_string_array + type: array + items: + type: string + default: '$' + enum: + - '>' + - '$' + in: header + description: Header parameter enum test (string array) + - name: enum_header_string + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + in: header + description: Header parameter enum test (string) + - name: enum_query_string_array + type: array + items: + type: string + default: '$' + enum: + - '>' + - '$' + in: query + description: Query parameter enum test (string array) + - name: enum_query_string + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + in: query description: Query parameter enum test (string) - name: enum_query_integer type: number @@ -667,6 +737,11 @@ paths: pattern: /[a-z]/i in: formData description: None + - name: pattern_without_delimiter + type: string + pattern: "^[A-Z].*" + in: formData + description: None required: true - name: byte type: string @@ -696,12 +771,17 @@ paths: minLength: 10 in: formData description: None + - name: callback + type: string + in: formData + description: None responses: '400': description: Invalid username supplied '404': description: User not found - + security: + - http_basic_test: [] securityDefinitions: petstore_auth: type: oauth2 @@ -714,6 +794,8 @@ securityDefinitions: type: apiKey name: api_key in: header + http_basic_test: + type: basic definitions: Order: type: object @@ -1018,6 +1100,16 @@ definitions: type: object additionalProperties: $ref: '#/definitions/Animal' + List: + type: object + properties: + 123-list: + type: string + Client: + type: object + properties: + client: + type: string ReadOnlyFirst: type: object properties: @@ -1111,6 +1203,31 @@ definitions: type: array items: type: number + EnumArrays: + type: object + properties: + just_symbol: + type: string + enum: + - ">=" + - "$" + array_enum: + type: array + items: + type: string + enum: + - fish + - crab + # comment out the following as 2d array of enum is not supported at the moment + #array_array_enum: + # type: array + # items: + # type: array + # items: + # type: string + # enum: + # - Cat + # - Dog externalDocs: description: Find out more about Swagger url: 'http://swagger.io' diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 24fcf4bf768..be0254ec3a2 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -114,7 +114,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -174,7 +174,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml index 73493835106..cd10223ba04 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml @@ -573,6 +573,8 @@ securityDefinitions: in: header definitions: Order: + title: Pet Order + description: An order for a pets from the pet store type: object properties: id: @@ -600,6 +602,8 @@ definitions: xml: name: Order Category: + title: Pet catehgry + description: A category for a pet type: object properties: id: @@ -610,6 +614,8 @@ definitions: xml: name: Category User: + title: a User + description: A User who is purchasing from the pet store type: object properties: id: @@ -634,6 +640,8 @@ definitions: xml: name: User Tag: + title: Pet Tag + description: A tag for a pet type: object properties: id: @@ -644,6 +652,8 @@ definitions: xml: name: Tag Pet: + title: a Pet + description: A pet for sale in the pet store type: object required: - name @@ -681,6 +691,8 @@ definitions: xml: name: Pet ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource type: object properties: code: diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/modules/swagger-codegen/src/test/resources/petstore.json b/modules/swagger-codegen/src/test/resources/petstore.json index 66762d74b2b..dd9b1f42edf 100644 --- a/modules/swagger-codegen/src/test/resources/petstore.json +++ b/modules/swagger-codegen/src/test/resources/petstore.json @@ -113,7 +113,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -163,7 +163,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 7304fdd04bc..c44e4c2afd0 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.2-SNAPSHOT ../.. swagger-generator diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index dc1cff0d320..ad6529bd36a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -13,6 +13,7 @@ import io.swagger.generator.model.ResponseCode; import io.swagger.generator.online.Generator; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; @@ -91,17 +92,21 @@ public Response generateClient( @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { String filename = Generator.generateClient(language, opts); - String scheme = request.getHeader("X-SSL"); - String port = ""; - if("1".equals(scheme)) { - scheme = "https"; - } - else { - scheme = request.getScheme(); - port = ":" + request.getServerPort(); + String host = System.getenv("GENERATOR_HOST"); + + if(StringUtils.isBlank(host)) { + String scheme = request.getHeader("X-SSL"); + String port = ""; + if("1".equals(scheme)) { + scheme = "https"; + } + else { + scheme = request.getScheme(); + port = ":" + request.getServerPort(); + } + host = scheme + "://" + request.getServerName() + port; } - String host = scheme + "://" + request.getServerName() + port; if (filename != null) { String code = String.valueOf(UUID.randomUUID().toString()); Generated g = new Generated(); diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java index bca63e37eed..c58844fb1da 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -22,6 +22,6 @@ public void getOptionsTest() throws ApiException { assertNotNull(options); final CliOption opt = options.get(CodegenConstants.LIBRARY); assertNotNull(opt); - assertEquals(opt.getDefault(), JavaClientCodegen.DEFAULT_LIBRARY); + assertEquals(opt.getDefault(), "okhttp-gson"); } } diff --git a/modules/swagger-generator/src/test/resources/petstore.json b/modules/swagger-generator/src/test/resources/petstore.json index 67c4d47292d..1617f8d0ae6 100644 --- a/modules/swagger-generator/src/test/resources/petstore.json +++ b/modules/swagger-generator/src/test/resources/petstore.json @@ -135,7 +135,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/xml", @@ -190,7 +190,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/xml", diff --git a/pom.xml b/pom.xml index c502c48914d..4f8a6f1219a 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.2-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -29,7 +29,7 @@ github - https://github.com/swagger-api/swagger-core/issues + https://github.com/swagger-api/swagger-codegen/issues @@ -104,23 +104,9 @@ - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - maven-compiler-plugin - 3.0 + 3.5.1 1.7 1.7 @@ -129,7 +115,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.4 + 3.0.2 @@ -144,18 +130,18 @@ org.apache.maven.plugins maven-site-plugin - 2.1 + 3.5.1 org.apache.maven.plugins maven-release-plugin - 2.1 + 2.5.3 org.apache.maven.plugins maven-javadoc-plugin - 2.10.3 + 2.10.4 true 1.7 @@ -176,7 +162,7 @@ org.apache.maven.plugins maven-source-plugin - 2.1.2 + 3.0.1 attach-sources @@ -283,7 +269,7 @@ - java-client + java-client-jersey1 env @@ -291,7 +277,7 @@ - samples/client/petstore/java/default + samples/client/petstore/java/jersey1 @@ -318,6 +304,18 @@ samples/client/petstore/java/okhttp-gson + + java-client-okhttp-gson-parcelable + + + env + java + + + + samples/client/petstore/java/okhttp-gson/parcelableModel + + java-client-retrofit @@ -558,6 +556,18 @@ samples/client/petstore/ruby + + go-client + + + env + java + + + + samples/client/petstore/go + + spring-mvc @@ -570,6 +580,66 @@ samples/server/petstore/spring-mvc + + springboot + + + env + java + + + + samples/server/petstore/springboot + + + + spring-cloud + + + env + java + + + + samples/client/petstore/spring-cloud + + + + scalatra-server + + + env + java + + + + samples/server/petstore/scalatra + + + + java-inflector + + + env + java + + + + samples/server/petstore/java-inflector + + + + java-undertowr + + + env + java + + + + samples/server/petstore/undertow + + samples @@ -581,30 +651,38 @@ + samples/client/petstore/ruby - samples/client/petstore/python - samples/client/petstore/typescript-fetch/tests/default - samples/client/petstore/typescript-fetch/builds/default - samples/client/petstore/typescript-fetch/builds/es6-target - samples/client/petstore/typescript-fetch/builds/with-npm-version - samples/client/petstore/typescript-angular - samples/client/petstore/typescript-node/npm samples/client/petstore/android/volley samples/client/petstore/clojure - samples/client/petstore/java/default + samples/client/petstore/go samples/client/petstore/java/feign + samples/client/petstore/java/jersey1 samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit samples/client/petstore/java/retrofit2 samples/client/petstore/java/retrofit2rx samples/client/petstore/javascript + samples/client/petstore/python samples/client/petstore/scala - samples/server/petstore/spring-mvc + samples/client/petstore/typescript-fetch/builds/default + samples/client/petstore/typescript-fetch/builds/es6-target + samples/client/petstore/typescript-fetch/builds/with-npm-version + samples/client/petstore/typescript-fetch/tests/default + samples/client/petstore/typescript-angular + samples/client/petstore/typescript-node/npm + + samples/server/petstore/java-inflector + samples/server/petstore/undertow samples/server/petstore/jaxrs/jersey1 samples/server/petstore/jaxrs/jersey2 samples/server/petstore/jaxrs-resteasy/default samples/server/petstore/jaxrs-resteasy/joda + samples/server/petstore/scalatra + samples/server/petstore/spring-mvc + samples/client/petstore/spring-cloud + samples/server/petstore/springboot @@ -627,7 +705,7 @@ org.apache.maven.plugins maven-jxr-plugin - 2.3 + 2.5 true @@ -635,7 +713,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 2.6 + 2.9 @@ -678,7 +756,7 @@ - 1.0.19 + 1.0.22 2.11.1 2.3.4 1.5.9 @@ -691,8 +769,8 @@ 3.2.1 1.12 6.9.6 - 2.18.1 - 1.19 + 2.19.1 + 1.25 0.9.10 diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln index 3f6c7053bf8..8dcf7f24348 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{29125490-71E4-47ED-B0D7-34505F58103C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{8CE139DF-64BC-4591-85F8-8506C2B67514}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{29125490-71E4-47ED-B0D7-34505F58103C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{29125490-71E4-47ED-B0D7-34505F58103C}.Debug|Any CPU.Build.0 = Debug|Any CPU -{29125490-71E4-47ED-B0D7-34505F58103C}.Release|Any CPU.ActiveCfg = Release|Any CPU -{29125490-71E4-47ED-B0D7-34505F58103C}.Release|Any CPU.Build.0 = Release|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs index 39b58c92731..eaf83ecaeae 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs @@ -1,9 +1,9 @@ - + - - + + diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/README.md b/samples/client/petstore-security-test/csharp/SwaggerClient/README.md index dc258722110..44f3ab7c368 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/README.md +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/README.md @@ -1,12 +1,12 @@ -# IO.Swagger - the C# library for the Swagger Petstore ' \" =end +# IO.Swagger - the C# library for the 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 - - This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- API version: 1.0.0 ' \" =end +- API version: 1.0.0 *_/ ' \" =end - - \\r\\n \\n \\r - SDK version: 1.0.0 -- Build date: 2016-06-29T22:47:27.264+08:00 +- Build date: 2016-07-13T18:16:08.689+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -14,8 +14,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - 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 +- [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 recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: ``` @@ -54,31 +54,33 @@ namespace Example { var apiInstance = new FakeApi(); - var testCodeInjectEnd = testCodeInjectEnd_example; // string | To test code injection ' \" =end (optional) + var testCodeInjectEndRnNR = testCodeInjectEndRnNR_example; // string | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r (optional) try { - // To test code injection ' \" =end - apiInstance.TestCodeInjectEnd(testCodeInjectEnd); + // To test code injection *_/ ' \" =end - - \\r\\n \\n \\r + apiInstance.TestCodeInjectEndRnNR(testCodeInjectEndRnNR); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestCodeInjectEnd: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestCodeInjectEndRnNR: " + e.Message ); } } } } ``` + ## Documentation for API Endpoints -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end - - \\r\\n \\n \\r/v2 *_/ ' \" =end - - \\r\\n \\n \\r* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**TestCodeInjectEnd**](docs/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection ' \" =end +*FakeApi* | [**TestCodeInjectEndRnNR**](docs/FakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r + ## Documentation for Models - [Model.ModelReturn](docs/ModelReturn.md) @@ -86,11 +88,10 @@ Class | Method | HTTP request | Description ## Documentation for Authorization - ### api_key - **Type**: API key -- **API key parameter name**: api_key */ ' " =end +- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r - **Location**: HTTP header ### petstore_auth @@ -99,6 +100,6 @@ Class | Method | HTTP request | Description - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - write:pets: modify pets in your account */ ' " =end - - read:pets: read your pets */ ' " =end + - write:pets: modify pets in your account */ ' " =end -- \r\n \n \r + - read:pets: read your pets */ ' " =end -- \r\n \n \r diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md index 962ba5fc6e0..39a951cbede 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md @@ -1,16 +1,17 @@ # IO.Swagger.Api.FakeApi -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end - - \\r\\n \\n \\r/v2 *_/ ' \" =end - - \\r\\n \\n \\r* Method | HTTP request | Description ------------- | ------------- | ------------- -[**TestCodeInjectEnd**](FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection ' \" =end +[**TestCodeInjectEndRnNR**](FakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r -# **TestCodeInjectEnd** -> void TestCodeInjectEnd (string testCodeInjectEnd = null) + +# **TestCodeInjectEndRnNR** +> void TestCodeInjectEndRnNR (string testCodeInjectEndRnNR = null) -To test code injection ' \" =end +To test code injection *_/ ' \" =end - - \\r\\n \\n \\r ### Example ```csharp @@ -22,22 +23,22 @@ using IO.Swagger.Model; namespace Example { - public class TestCodeInjectEndExample + public class TestCodeInjectEndRnNRExample { public void main() { var apiInstance = new FakeApi(); - var testCodeInjectEnd = testCodeInjectEnd_example; // string | To test code injection ' \" =end (optional) + var testCodeInjectEndRnNR = testCodeInjectEndRnNR_example; // string | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r (optional) try { - // To test code injection ' \" =end - apiInstance.TestCodeInjectEnd(testCodeInjectEnd); + // To test code injection *_/ ' \" =end - - \\r\\n \\n \\r + apiInstance.TestCodeInjectEndRnNR(testCodeInjectEndRnNR); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestCodeInjectEnd: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestCodeInjectEndRnNR: " + e.Message ); } } } @@ -48,7 +49,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **string**| To test code injection ' \" =end | [optional] + **testCodeInjectEndRnNR** | **string**| To test code injection *_/ ' \" =end - - \\r\\n \\n \\r | [optional] ### Return type @@ -60,8 +61,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ ' =end - - **Accept**: application/json, */ ' =end + - **Content-Type**: application/json, *_/ ' =end - - + - **Accept**: application/json, *_/ ' =end - - [[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-security-test/csharp/SwaggerClient/docs/ModelReturn.md b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md index 57af1de2bdc..ba83e94b8ce 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md @@ -3,7 +3,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_Return** | **int?** | property description ' \" =end | [optional] +**_Return** | **int?** | property description *_/ ' \" =end - - \\r\\n \\n \\r | [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-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 35bf372e00a..dc7be6546d9 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -1,11 +1,11 @@ + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + 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 + 2.3.2 + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.10 + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + + 2.10.4 + 1.2 + 2.2 + 1.19 + 1.5.8 + 1.0.5 + 1.0.0 + 2.4.2 + + 4.8.1 + 3.1.5 + 2.2.4 + + UTF-8 + + diff --git a/samples/client/petstore-security-test/scala/settings.gradle b/samples/client/petstore-security-test/scala/settings.gradle new file mode 100644 index 00000000000..5452c701c0e --- /dev/null +++ b/samples/client/petstore-security-test/scala/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-scala-client" \ No newline at end of file diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala new file mode 100644 index 00000000000..22f3dac7cf8 --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -0,0 +1,226 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client + +import com.sun.jersey.api.client.Client +import com.sun.jersey.api.client.ClientResponse +import com.sun.jersey.api.client.config.ClientConfig +import com.sun.jersey.api.client.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.core.util.MultivaluedMapImpl +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable.HashMap + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: HashMap[String, String] = HashMap(), + hostMap: HashMap[String, Client] = HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false) { + + var defaultHeaders: HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => { + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 1) + else s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case "list" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case _ => { + json match { + case e: String if ("\"\"" == e) => null + case _ => mapper.readValue(json, cls) + } + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else null + } + + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.map(p => { + headerParams.contains(p._1) match { + case true => // override default with supplied header + case false => if (p._2 != null) builder.header(p._1, p._2) + } + }) + var formData: MultivaluedMapImpl = null + if(contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.map(p => formData.add(p._1, p._2)) + } + + val response: ClientResponse = method match { + case "GET" => { + builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + } + case "POST" => { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName()) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } + else { + if(body == null) builder.post(classOf[ClientResponse], serialize(body)) + else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body == null) builder.put(classOf[ClientResponse], null) + else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => { + builder.delete(classOf[ClientResponse]) + } + case _ => null + } + response.getStatusInfo().getStatusCode() match { + case 204 => "" + case code: Int if (Range(200, 299).contains(code)) => { + response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "" + } + } + case _ => { + val entity = response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "no data" + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + entity) + } + } + } + + def getClient(host: String): Client = { + hostMap.contains(host) match { + case true => hostMap(host) + case false => { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + } + + def newClient(host: String): Client = asyncHttpClient match { + case true => { + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import com.ning.http.client.Realm + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config.getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } + case _ => Client.create() + } +} + +object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = HashMap(), + hostMap = HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) 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 new file mode 100644 index 00000000000..daec25f863b --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala @@ -0,0 +1,92 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api + +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + * @return void + */ + def testCodeInject * ' " =end rn n r (testCodeInjectEndRnNR: String) = { + // create path and map variables + val path = "/fake".replaceAll("\\{format\\}","json") + val contentTypes = List("application/json", "*/ ' =end + + ", "application/json") + val contentType = contentTypes(0) + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] + + + + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + mp.field("test code inject */ ' " =end \r\n \n \r", testCodeInjectEndRnNR.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + + postBody = mp + } + else { + formParams += "test code inject */ ' " =end \r\n \n \r" -> testCodeInjectEndRnNR.toString() + } + + try { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} 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 new file mode 100644 index 00000000000..08aaff0573a --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -0,0 +1,32 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.model + + + + +case class ModelReturn ( + /* property description *_/ ' \" =end \\r\\n \\n \\r */ + _return: Integer) diff --git a/samples/client/petstore-security-test/swift/.gitignore b/samples/client/petstore-security-test/swift/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore-security-test/swift/.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-security-test/swift/.swagger-codegen-ignore b/samples/client/petstore-security-test/swift/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/swift/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/swift/Cartfile b/samples/client/petstore-security-test/swift/Cartfile new file mode 100644 index 00000000000..3d90db16891 --- /dev/null +++ b/samples/client/petstore-security-test/swift/Cartfile @@ -0,0 +1 @@ +github "Alamofire/Alamofire" >= 3.1.0 diff --git a/samples/client/petstore-security-test/swift/LICENSE b/samples/client/petstore-security-test/swift/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/swift/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/swift/SwaggerClient.podspec b/samples/client/petstore-security-test/swift/SwaggerClient.podspec new file mode 100644 index 00000000000..4786bf4084e --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient.podspec @@ -0,0 +1,10 @@ +Pod::Spec.new do |s| + s.name = 'SwaggerClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.license = 'Apache License, Version 2.0' + s.source_files = 'SwaggerClient/Classes/Swaggers/**/*.swift' + s.dependency 'Alamofire', '~> 3.1.5' +end diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..23e727b6b54 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,40 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..afc7afbc094 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,73 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public class SwaggerClientAPI { + public static var basePath = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +public class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in (encoded as! [AnyObject]).enumerate() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +public class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + + addHeaders(SwaggerClientAPI.customHeaders) + } + + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } + + public func addHeader(name name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + public func addCredential() -> Self { + self.credential = SwaggerClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 00000000000..0d35a764773 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,51 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +public class FakeAPI: APIBase { + /** + To test code injection *_/ ' \" =end \\r\\n \\n \\r + + - parameter testCodeInjectEndRnNR: (form) To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func testCodeInjectEndRnNR(testCodeInjectEndRnNR testCodeInjectEndRnNR: String? = nil, completion: ((error: ErrorType?) -> Void)) { + testCodeInjectEndRnNRWithRequestBuilder(testCodeInjectEndRnNR: testCodeInjectEndRnNR).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + To test code injection *_/ ' \" =end \\r\\n \\n \\r + - PUT /fake + + - parameter testCodeInjectEndRnNR: (form) To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + + - returns: RequestBuilder + */ + public class func testCodeInjectEndRnNRWithRequestBuilder(testCodeInjectEndRnNR testCodeInjectEndRnNR: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = SwaggerClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "test code inject */ ' " =end \r\n \n \r": testCodeInjectEndRnNR + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: false) + } + +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..2faa0a6f24d --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,112 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, error: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + request.validate().responseJSON(options: .AllowFragments) { response in + managerStore.removeValueForKey(managerId) + + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..fed87969388 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,74 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(int: self) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + + +private let dateFormatter: NSDateFormatter = { + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} + + diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..3f70e2a1c5e --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift @@ -0,0 +1,147 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictionary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { + initialize() + if T.self is Int32.Type && source is NSNumber { + return source.intValue as! T; + } + if T.self is Int64.Type && source is NSNumber { + return source.longLongValue as! T; + } + if source is T { + return source as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + + } + if let sourceInt = source as? Int { + // treat as a java date + return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) ) + } + fatalError("formatter failed to parse \(source)") + } + + // Decoder for [Return] + Decoders.addDecoder(clazz: [Return].self) { (source: AnyObject) -> [Return] in + return Decoders.decode(clazz: [Return].self, source: source) + } + // Decoder for Return + Decoders.addDecoder(clazz: Return.self) { (source: AnyObject) -> Return in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Return() + instance._return = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"]) + return instance + } + } + } +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 00000000000..30c76776b83 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,25 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r */ +public class Return: JSONEncodable { + /** property description *_/ ' \" =end \\r\\n \\n \\r */ + public var _return: Int32? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["return"] = self._return?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore-security-test/swift/git_push.sh b/samples/client/petstore-security-test/swift/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/swift/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-security-test/typescript-angular/.gitignore b/samples/client/petstore-security-test/typescript-angular/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts new file mode 100644 index 00000000000..7e22ee8d0ed --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts @@ -0,0 +1,85 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +namespace API.Client { + 'use strict'; + + export class FakeApi { + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/fake'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + + let httpRequestParams: any = { + method: 'PUT', + url: localVarPath, + json: false, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + } +} diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts new file mode 100644 index 00000000000..7509de72a30 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts @@ -0,0 +1,41 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +namespace API.Client { + 'use strict'; + + /** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ + export interface ModelReturn { + + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + "return"?: number; + } + +} diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts new file mode 100644 index 00000000000..258d4403228 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts @@ -0,0 +1,3 @@ +/// + +/// diff --git a/samples/client/petstore-security-test/typescript-angular/LICENSE b/samples/client/petstore-security-test/typescript-angular/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-angular/git_push.sh b/samples/client/petstore-security-test/typescript-angular/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/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-security-test/typescript-angular2/.gitignore b/samples/client/petstore-security-test/typescript-angular2/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-angular2/LICENSE b/samples/client/petstore-security-test/typescript-angular2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts new file mode 100644 index 00000000000..88b8e7a6562 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts @@ -0,0 +1,79 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import * as models from '../model/models'; +import 'rxjs/Rx'; + +/* tslint:disable:no-unused-variable member-ordering */ + +'use strict'; + +@Injectable() +export class FakeApi { + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + public defaultHeaders : Headers = new Headers(); + + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : Observable<{}> { + const path = this.basePath + '/fake'; + + let queryParameters = new URLSearchParams(); + let headerParams = this.defaultHeaders; + let formParams = new URLSearchParams(); + + headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); + + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + + let requestOptions: RequestOptionsArgs = { + method: 'PUT', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = formParams.toString(); + + return this.http.request(path, requestOptions) + .map((response: Response) => { + if (response.status === 204) { + return undefined; + } else { + return response.json(); + } + }); + } + +} diff --git a/samples/client/petstore-security-test/typescript-angular2/api/api.ts b/samples/client/petstore-security-test/typescript-angular2/api/api.ts new file mode 100644 index 00000000000..9525ab85127 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/api/api.ts @@ -0,0 +1 @@ +export * from './FakeApi'; diff --git a/samples/client/petstore-security-test/typescript-angular2/git_push.sh b/samples/client/petstore-security-test/typescript-angular2/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/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-security-test/typescript-angular2/index.ts b/samples/client/petstore-security-test/typescript-angular2/index.ts new file mode 100644 index 00000000000..557365516ad --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts new file mode 100644 index 00000000000..23c982f6888 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts @@ -0,0 +1,38 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; +import * as models from './models'; + +/** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ +export interface ModelReturn { + + + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + return?: number; +} diff --git a/samples/client/petstore-security-test/typescript-angular2/model/models.ts b/samples/client/petstore-security-test/typescript-angular2/model/models.ts new file mode 100644 index 00000000000..df8a2d48008 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/model/models.ts @@ -0,0 +1 @@ +export * from './ModelReturn'; diff --git a/samples/client/petstore-security-test/typescript-fetch/.gitignore b/samples/client/petstore-security-test/typescript-fetch/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-fetch/LICENSE b/samples/client/petstore-security-test/typescript-fetch/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-fetch/README.md b/samples/client/petstore-security-test/typescript-fetch/README.md new file mode 100644 index 00000000000..664e1755933 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink 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 new file mode 100644 index 00000000000..b439ec1d8ed --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -0,0 +1,125 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +/** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ +export interface ModelReturn { + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + "return"?: number; +} + + + +/** + * FakeApi - fetch parameter creator + */ +export const FakeApiFetchParamCreactor = { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): FetchArgs { + const baseUrl = `/fake`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "test code inject */ ' " =end \r\n \n \r": params.test code inject * ' " =end rn n r, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * FakeApi - functional programming interface + */ +export const FakeApiFp = { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = FakeApiFetchParamCreactor.testCodeInjectEndRnNR(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * FakeApi - object-oriented interface + */ +export class FakeApi extends BaseAPI { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }) { + return FakeApiFp.testCodeInjectEndRnNR(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore-security-test/typescript-fetch/git_push.sh b/samples/client/petstore-security-test/typescript-fetch/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/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-security-test/typescript-fetch/package.json b/samples/client/petstore-security-test/typescript-fetch/package.json new file mode 100644 index 00000000000..97e572353a3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/package.json @@ -0,0 +1,19 @@ +{ + "name": "typescript-fetch-api", + "version": "0.0.0", + "license": "Apache-2.0", + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "core-js": "^2.4.0", + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "prepublish" : "typings install && tsc" + }, + "devDependencies": { + "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 new file mode 100644 index 00000000000..72ff2567206 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/tsconfig.json @@ -0,0 +1,17 @@ +{ + "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/typings.json b/samples/client/petstore-security-test/typescript-fetch/typings.json new file mode 100644 index 00000000000..a82ea152b4a --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/typings.json @@ -0,0 +1,9 @@ +{ + "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/.gitignore b/samples/client/petstore-security-test/typescript-node/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-node/LICENSE b/samples/client/petstore-security-test/typescript-node/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-node/api.ts b/samples/client/petstore-security-test/typescript-node/api.ts new file mode 100644 index 00000000000..4afd3239aa3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/api.ts @@ -0,0 +1,193 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import request = require('request'); +import http = require('http'); +import Promise = require('bluebird'); + +let defaultBasePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +/** +* Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r +*/ +export class ModelReturn { + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + 'return': number; +} + + +export interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +export class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +export class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +export class OAuth implements Authentication { + public accessToken: string; + + applyToRequest(requestOptions: request.Options): void { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } +} + +export class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +export enum FakeApiApiKeys { + api_key, +} + +export class FakeApi { + protected basePath = defaultBasePath; + protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key */ ' " =end \r\n \n \r'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + public setApiKey(key: FakeApiApiKeys, value: string) { + this.authentications[FakeApiApiKeys[key]].apiKey = value; + } + + set accessToken(token: string) { + this.authentications.petstore_auth.accessToken = token; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + 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 = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + if (test code inject * ' " =end rn n r !== undefined) { + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + } + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} diff --git a/samples/client/petstore-security-test/typescript-node/git_push.sh b/samples/client/petstore-security-test/typescript-node/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/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/akka-scala/.swagger-codegen-ignore b/samples/client/petstore/akka-scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/akka-scala/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# 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/akka-scala/LICENSE b/samples/client/petstore/akka-scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/akka-scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/akka-scala/pom.xml b/samples/client/petstore/akka-scala/pom.xml index b625621f58c..af37db6dbab 100644 --- a/samples/client/petstore/akka-scala/pom.xml +++ b/samples/client/petstore/akka-scala/pom.xml @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.8 + 1.5.9 1.0.0 4.8.1 diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala index 31a9325c6f8..0b996a89cc5 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala @@ -9,11 +9,10 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class ApiResponse ( code: Option[Int], `type`: Option[String], - message: Option[String]) - extends ApiModel + message: Option[String] +) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala index 6d14fc12276..48af020f18d 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -9,10 +9,9 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Category ( id: Option[Long], - name: Option[String]) - extends ApiModel + name: Option[String] +) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala index 7ed7ae6109c..3c2d7a255e2 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -9,7 +9,6 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Order ( id: Option[Long], petId: Option[Long], @@ -17,19 +16,17 @@ case class Order ( shipDate: Option[DateTime], /* Order Status */ status: Option[OrderEnums.Status], - complete: Option[Boolean]) - extends ApiModel + complete: Option[Boolean] +) extends ApiModel object OrderEnums { type Status = Status.Value - object Status extends Enumeration { val Placed = Value("placed") val Approved = Value("approved") val Delivered = Value("delivered") } - } diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala index 0b8cf84d49a..2adadb61eaa 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -9,7 +9,6 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Pet ( id: Option[Long], category: Option[Category], @@ -17,19 +16,17 @@ case class Pet ( photoUrls: Seq[String], tags: Option[Seq[Tag]], /* pet status in the store */ - status: Option[PetEnums.Status]) - extends ApiModel + status: Option[PetEnums.Status] +) extends ApiModel object PetEnums { type Status = Status.Value - object Status extends Enumeration { val Available = Value("available") val Pending = Value("pending") val Sold = Value("sold") } - } diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala index 5a4b2f412c7..6658e733b4e 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -9,10 +9,9 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Tag ( id: Option[Long], - name: Option[String]) - extends ApiModel + name: Option[String] +) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala index 2dc7325c465..6db0c80fc33 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -9,7 +9,6 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class User ( id: Option[Long], username: Option[String], @@ -19,7 +18,7 @@ case class User ( password: Option[String], phone: Option[String], /* User Status */ - userStatus: Option[Int]) - extends ApiModel + userStatus: Option[Int] +) extends ApiModel diff --git a/samples/client/petstore/android/httpclient/.swagger-codegen-ignore b/samples/client/petstore/android/httpclient/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/android/httpclient/.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/android/httpclient/LICENSE b/samples/client/petstore/android/httpclient/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/android/httpclient/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/android/httpclient/README.md b/samples/client/petstore/android/httpclient/README.md index 65931066a32..3c9dcf27af0 100644 --- a/samples/client/petstore/android/httpclient/README.md +++ b/samples/client/petstore/android/httpclient/README.md @@ -134,7 +134,7 @@ Authentication schemes defined for the API: ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/samples/client/petstore/android/httpclient/docs/PetApi.md b/samples/client/petstore/android/httpclient/docs/PetApi.md index f0f8ad40fbe..e7b393c8ea7 100644 --- a/samples/client/petstore/android/httpclient/docs/PetApi.md +++ b/samples/client/petstore/android/httpclient/docs/PetApi.md @@ -106,7 +106,7 @@ null (empty response body) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```java @@ -128,7 +128,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] [enum: available, pending, sold] ### Return type @@ -149,7 +149,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```java diff --git a/samples/client/petstore/android/httpclient/git_push.sh b/samples/client/petstore/android/httpclient/git_push.sh index ed374619b13..792320114fb 100644 --- a/samples/client/petstore/android/httpclient/git_push.sh +++ b/samples/client/petstore/android/httpclient/git_push.sh @@ -28,7 +28,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/android/httpclient/pom.xml b/samples/client/petstore/android/httpclient/pom.xml index afedf8f3027..a9bff313266 100644 --- a/samples/client/petstore/android/httpclient/pom.xml +++ b/samples/client/petstore/android/httpclient/pom.xml @@ -145,11 +145,11 @@ - 1.5.8 + 1.5.9 2.3.1 4.8.1 1.0.0 4.8.1 4.3.6 - \ No newline at end of file + diff --git a/samples/client/petstore/android/httpclient/settings.gradle b/samples/client/petstore/android/httpclient/settings.gradle index 6a6796bf9fe..599d6882189 100644 --- a/samples/client/petstore/android/httpclient/settings.gradle +++ b/samples/client/petstore/android/httpclient/settings.gradle @@ -1 +1 @@ -rootProject.name = "swagger-android-client" \ No newline at end of file +rootProject.name = "swagger-android-client" diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java index 31bc8a0978a..5b2b0e7dbf5 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class ApiException extends Exception { @@ -14,16 +38,16 @@ public ApiException(int code, String message) { public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } - + public String getMessage() { return message; } - + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java index ecb787006dd..7118a48d50e 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import org.apache.http.*; @@ -15,6 +39,8 @@ import org.apache.http.util.EntityUtils; import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.net.URLEncoder; @@ -24,8 +50,6 @@ import java.util.HashMap; import java.util.List; import java.util.ArrayList; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; @@ -206,7 +230,11 @@ public void addDefaultHeader(String key, String value) { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java index cb97056dbc9..e880e64070b 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import org.apache.http.client.methods.*; @@ -13,4 +37,4 @@ public HttpPatch(final String url) { public String getMethod() { return METHOD_PATCH; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java index 2710fb5a99b..d9c600b04c9 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class Pair { diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java index 52e84575ad3..086378eb0ca 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiException; @@ -144,7 +168,7 @@ public void deletePet (Long petId, String apiKey) throws ApiException { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter * @return List */ @@ -194,7 +218,7 @@ public List findPetsByStatus (List status) throws ApiException { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by * @return List */ diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java index d20c70ad997..0672d5c8d5c 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiException; diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java index 5f61ba724ae..8a2c64ba9c4 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiException; diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java index f5d5ea86b63..eb9f643efe0 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java @@ -43,15 +43,15 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return (id == null ? category.id == null : id.equals(category.id)) && - (name == null ? category.name == null : name.equals(category.name)); + return (this.id == null ? category.id == null : this.id.equals(category.id)) && + (this.name == null ? category.name == null : this.name.equals(category.name)); } - @Override + @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java index f184238f717..5fe60f1bf56 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java @@ -96,23 +96,23 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return (id == null ? order.id == null : id.equals(order.id)) && - (petId == null ? order.petId == null : petId.equals(order.petId)) && - (quantity == null ? order.quantity == null : quantity.equals(order.quantity)) && - (shipDate == null ? order.shipDate == null : shipDate.equals(order.shipDate)) && - (status == null ? order.status == null : status.equals(order.status)) && - (complete == null ? order.complete == null : complete.equals(order.complete)); + return (this.id == null ? order.id == null : this.id.equals(order.id)) && + (this.petId == null ? order.petId == null : this.petId.equals(order.petId)) && + (this.quantity == null ? order.quantity == null : this.quantity.equals(order.quantity)) && + (this.shipDate == null ? order.shipDate == null : this.shipDate.equals(order.shipDate)) && + (this.status == null ? order.status == null : this.status.equals(order.status)) && + (this.complete == null ? order.complete == null : this.complete.equals(order.complete)); } - @Override + @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (petId == null ? 0: petId.hashCode()); - result = 31 * result + (quantity == null ? 0: quantity.hashCode()); - result = 31 * result + (shipDate == null ? 0: shipDate.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); - result = 31 * result + (complete == null ? 0: complete.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.petId == null ? 0: this.petId.hashCode()); + result = 31 * result + (this.quantity == null ? 0: this.quantity.hashCode()); + result = 31 * result + (this.shipDate == null ? 0: this.shipDate.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.complete == null ? 0: this.complete.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java index e471a300a31..8795964a6b3 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java @@ -98,23 +98,23 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return (id == null ? pet.id == null : id.equals(pet.id)) && - (category == null ? pet.category == null : category.equals(pet.category)) && - (name == null ? pet.name == null : name.equals(pet.name)) && - (photoUrls == null ? pet.photoUrls == null : photoUrls.equals(pet.photoUrls)) && - (tags == null ? pet.tags == null : tags.equals(pet.tags)) && - (status == null ? pet.status == null : status.equals(pet.status)); + return (this.id == null ? pet.id == null : this.id.equals(pet.id)) && + (this.category == null ? pet.category == null : this.category.equals(pet.category)) && + (this.name == null ? pet.name == null : this.name.equals(pet.name)) && + (this.photoUrls == null ? pet.photoUrls == null : this.photoUrls.equals(pet.photoUrls)) && + (this.tags == null ? pet.tags == null : this.tags.equals(pet.tags)) && + (this.status == null ? pet.status == null : this.status.equals(pet.status)); } - @Override + @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (category == null ? 0: category.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); - result = 31 * result + (photoUrls == null ? 0: photoUrls.hashCode()); - result = 31 * result + (tags == null ? 0: tags.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.category == null ? 0: this.category.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); + result = 31 * result + (this.photoUrls == null ? 0: this.photoUrls.hashCode()); + result = 31 * result + (this.tags == null ? 0: this.tags.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java index 722e9194eb2..3729c3674fb 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java @@ -43,15 +43,15 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return (id == null ? tag.id == null : id.equals(tag.id)) && - (name == null ? tag.name == null : name.equals(tag.name)); + return (this.id == null ? tag.id == null : this.id.equals(tag.id)) && + (this.name == null ? tag.name == null : this.name.equals(tag.name)); } - @Override + @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java index 4f0a64671e2..4f789b5e359 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java @@ -116,27 +116,27 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return (id == null ? user.id == null : id.equals(user.id)) && - (username == null ? user.username == null : username.equals(user.username)) && - (firstName == null ? user.firstName == null : firstName.equals(user.firstName)) && - (lastName == null ? user.lastName == null : lastName.equals(user.lastName)) && - (email == null ? user.email == null : email.equals(user.email)) && - (password == null ? user.password == null : password.equals(user.password)) && - (phone == null ? user.phone == null : phone.equals(user.phone)) && - (userStatus == null ? user.userStatus == null : userStatus.equals(user.userStatus)); + return (this.id == null ? user.id == null : this.id.equals(user.id)) && + (this.username == null ? user.username == null : this.username.equals(user.username)) && + (this.firstName == null ? user.firstName == null : this.firstName.equals(user.firstName)) && + (this.lastName == null ? user.lastName == null : this.lastName.equals(user.lastName)) && + (this.email == null ? user.email == null : this.email.equals(user.email)) && + (this.password == null ? user.password == null : this.password.equals(user.password)) && + (this.phone == null ? user.phone == null : this.phone.equals(user.phone)) && + (this.userStatus == null ? user.userStatus == null : this.userStatus.equals(user.userStatus)); } - @Override + @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (username == null ? 0: username.hashCode()); - result = 31 * result + (firstName == null ? 0: firstName.hashCode()); - result = 31 * result + (lastName == null ? 0: lastName.hashCode()); - result = 31 * result + (email == null ? 0: email.hashCode()); - result = 31 * result + (password == null ? 0: password.hashCode()); - result = 31 * result + (phone == null ? 0: phone.hashCode()); - result = 31 * result + (userStatus == null ? 0: userStatus.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.username == null ? 0: this.username.hashCode()); + result = 31 * result + (this.firstName == null ? 0: this.firstName.hashCode()); + result = 31 * result + (this.lastName == null ? 0: this.lastName.hashCode()); + result = 31 * result + (this.email == null ? 0: this.email.hashCode()); + result = 31 * result + (this.password == null ? 0: this.password.hashCode()); + result = 31 * result + (this.phone == null ? 0: this.phone.hashCode()); + result = 31 * result + (this.userStatus == null ? 0: this.userStatus.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/.swagger-codegen-ignore b/samples/client/petstore/android/volley/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/android/volley/.swagger-codegen-ignore +++ b/samples/client/petstore/android/volley/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index e4aa4748243..c92f468b12b 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -134,7 +134,7 @@ Authentication schemes defined for the API: ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/samples/client/petstore/android/volley/build.gradle b/samples/client/petstore/android/volley/build.gradle index ab26beea6f9..64e2d8cc991 100644 --- a/samples/client/petstore/android/volley/build.gradle +++ b/samples/client/petstore/android/volley/build.gradle @@ -56,7 +56,7 @@ ext { httpmime_version = "4.5.2" httpcore_version = "4.4.4" httpclient_version = "4.3.3" - volley_version = "1.0.19" + volley_version = "1.0.0" junit_version = "4.12" robolectric_version = "3.0" concurrent_unit_version = "0.4.2" @@ -68,7 +68,7 @@ dependencies { compile "org.apache.httpcomponents:httpcore:$httpcore_version" compile "org.apache.httpcomponents:httpmime:$httpmime_version" compile "org.apache.httpcomponents:httpclient-android:$httpclient_version" - compile "com.mcxiaoke.volley:library:${volley_version}@aar" + compile "com.android.volley:volley:${volley_version}" testCompile "junit:junit:$junit_version" testCompile "org.robolectric:robolectric:${robolectric_version}" testCompile "net.jodah:concurrentunit:${concurrent_unit_version}" diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index f0f8ad40fbe..e7b393c8ea7 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -106,7 +106,7 @@ null (empty response body) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```java @@ -128,7 +128,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] [enum: available, pending, sold] ### Return type @@ -149,7 +149,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```java diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java index 6147e873178..5b2b0e7dbf5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class ApiException extends Exception { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java index cad5981703f..e1e32e370a3 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import com.android.volley.Cache; +import com.android.volley.DefaultRetryPolicy; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; @@ -18,6 +43,7 @@ import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -212,6 +238,7 @@ private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDel } public static ApiInvoker getInstance() { + if (INSTANCE == null) initializeInstance(); return INSTANCE; } @@ -220,7 +247,11 @@ public void addDefaultHeader(String key, String value) { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { @@ -476,7 +507,12 @@ else if ("PATCH".equals(method)) { } else { request = new PatchRequest(url, headers, null, null, stringRequest, errorListener); } - } + } + + if (request != null) { + request.setRetryPolicy(new DefaultRetryPolicy((int)TimeUnit.SECONDS.toMillis(this.connectionTimeout), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); + } + return request; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java index e725cf3291d..943da4de741 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java @@ -1,10 +1,39 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; +import java.util.Date; import io.swagger.client.model.*; public class JsonUtil { @@ -14,6 +43,11 @@ public class JsonUtil { gsonBuilder = new GsonBuilder(); gsonBuilder.serializeNulls(); gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); } public static Gson getGson() { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java index 2710fb5a99b..d9c600b04c9 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class Pair { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index c76ce6262bc..ae9bcead7c5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiInvoker; @@ -303,7 +327,7 @@ public void onErrorResponse(VolleyError error) { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter * @return List */ @@ -368,7 +392,7 @@ public List findPetsByStatus (List status) throws TimeoutException, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public void findPetsByStatus (List status, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { @@ -430,7 +454,7 @@ public void onErrorResponse(VolleyError error) { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by * @return List */ @@ -495,7 +519,7 @@ public List findPetsByTags (List tags) throws TimeoutException, Exe /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public void findPetsByTags (List tags, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java index e39a1b01d52..b2ae037fed4 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiInvoker; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java index 18eb24777b4..d7ca46d3c66 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiInvoker; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 28f59159d4d..9f30bc7dff7 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -52,9 +76,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..705f80a876e 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index c203adfbd2e..586e5a31b5d 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java index f3537ac56fc..7cdc4f56473 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java @@ -1,12 +1,34 @@ -package io.swagger.client.model; +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.swagger.client.model; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -43,15 +65,15 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return (id == null ? category.id == null : id.equals(category.id)) && - (name == null ? category.name == null : name.equals(category.name)); + return (this.id == null ? category.id == null : this.id.equals(category.id)) && + (this.name == null ? category.name == null : this.name.equals(category.name)); } @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java index 0054dbc1ba8..7f8554374d7 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java @@ -1,13 +1,35 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; import java.util.Date; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -96,23 +118,23 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return (id == null ? order.id == null : id.equals(order.id)) && - (petId == null ? order.petId == null : petId.equals(order.petId)) && - (quantity == null ? order.quantity == null : quantity.equals(order.quantity)) && - (shipDate == null ? order.shipDate == null : shipDate.equals(order.shipDate)) && - (status == null ? order.status == null : status.equals(order.status)) && - (complete == null ? order.complete == null : complete.equals(order.complete)); + return (this.id == null ? order.id == null : this.id.equals(order.id)) && + (this.petId == null ? order.petId == null : this.petId.equals(order.petId)) && + (this.quantity == null ? order.quantity == null : this.quantity.equals(order.quantity)) && + (this.shipDate == null ? order.shipDate == null : this.shipDate.equals(order.shipDate)) && + (this.status == null ? order.status == null : this.status.equals(order.status)) && + (this.complete == null ? order.complete == null : this.complete.equals(order.complete)); } @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (petId == null ? 0: petId.hashCode()); - result = 31 * result + (quantity == null ? 0: quantity.hashCode()); - result = 31 * result + (shipDate == null ? 0: shipDate.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); - result = 31 * result + (complete == null ? 0: complete.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.petId == null ? 0: this.petId.hashCode()); + result = 31 * result + (this.quantity == null ? 0: this.quantity.hashCode()); + result = 31 * result + (this.shipDate == null ? 0: this.shipDate.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.complete == null ? 0: this.complete.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java index b9d996cd764..492f54dcd58 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java @@ -1,15 +1,37 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; import io.swagger.client.model.Category; import io.swagger.client.model.Tag; import java.util.*; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -98,23 +120,23 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return (id == null ? pet.id == null : id.equals(pet.id)) && - (category == null ? pet.category == null : category.equals(pet.category)) && - (name == null ? pet.name == null : name.equals(pet.name)) && - (photoUrls == null ? pet.photoUrls == null : photoUrls.equals(pet.photoUrls)) && - (tags == null ? pet.tags == null : tags.equals(pet.tags)) && - (status == null ? pet.status == null : status.equals(pet.status)); + return (this.id == null ? pet.id == null : this.id.equals(pet.id)) && + (this.category == null ? pet.category == null : this.category.equals(pet.category)) && + (this.name == null ? pet.name == null : this.name.equals(pet.name)) && + (this.photoUrls == null ? pet.photoUrls == null : this.photoUrls.equals(pet.photoUrls)) && + (this.tags == null ? pet.tags == null : this.tags.equals(pet.tags)) && + (this.status == null ? pet.status == null : this.status.equals(pet.status)); } @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (category == null ? 0: category.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); - result = 31 * result + (photoUrls == null ? 0: photoUrls.hashCode()); - result = 31 * result + (tags == null ? 0: tags.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.category == null ? 0: this.category.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); + result = 31 * result + (this.photoUrls == null ? 0: this.photoUrls.hashCode()); + result = 31 * result + (this.tags == null ? 0: this.tags.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java index 05b540d1617..45d3b965226 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java @@ -1,12 +1,34 @@ -package io.swagger.client.model; +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.swagger.client.model; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -43,15 +65,15 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return (id == null ? tag.id == null : id.equals(tag.id)) && - (name == null ? tag.name == null : name.equals(tag.name)); + return (this.id == null ? tag.id == null : this.id.equals(tag.id)) && + (this.name == null ? tag.name == null : this.name.equals(tag.name)); } @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java index 4875b146616..79ebc1d607c 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java @@ -1,12 +1,34 @@ -package io.swagger.client.model; +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.swagger.client.model; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -116,27 +138,27 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return (id == null ? user.id == null : id.equals(user.id)) && - (username == null ? user.username == null : username.equals(user.username)) && - (firstName == null ? user.firstName == null : firstName.equals(user.firstName)) && - (lastName == null ? user.lastName == null : lastName.equals(user.lastName)) && - (email == null ? user.email == null : email.equals(user.email)) && - (password == null ? user.password == null : password.equals(user.password)) && - (phone == null ? user.phone == null : phone.equals(user.phone)) && - (userStatus == null ? user.userStatus == null : userStatus.equals(user.userStatus)); + return (this.id == null ? user.id == null : this.id.equals(user.id)) && + (this.username == null ? user.username == null : this.username.equals(user.username)) && + (this.firstName == null ? user.firstName == null : this.firstName.equals(user.firstName)) && + (this.lastName == null ? user.lastName == null : this.lastName.equals(user.lastName)) && + (this.email == null ? user.email == null : this.email.equals(user.email)) && + (this.password == null ? user.password == null : this.password.equals(user.password)) && + (this.phone == null ? user.phone == null : this.phone.equals(user.phone)) && + (this.userStatus == null ? user.userStatus == null : this.userStatus.equals(user.userStatus)); } @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (username == null ? 0: username.hashCode()); - result = 31 * result + (firstName == null ? 0: firstName.hashCode()); - result = 31 * result + (lastName == null ? 0: lastName.hashCode()); - result = 31 * result + (email == null ? 0: email.hashCode()); - result = 31 * result + (password == null ? 0: password.hashCode()); - result = 31 * result + (phone == null ? 0: phone.hashCode()); - result = 31 * result + (userStatus == null ? 0: userStatus.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.username == null ? 0: this.username.hashCode()); + result = 31 * result + (this.firstName == null ? 0: this.firstName.hashCode()); + result = 31 * result + (this.lastName == null ? 0: this.lastName.hashCode()); + result = 31 * result + (this.email == null ? 0: this.email.hashCode()); + result = 31 * result + (this.password == null ? 0: this.password.hashCode()); + result = 31 * result + (this.phone == null ? 0: this.phone.hashCode()); + result = 31 * result + (this.userStatus == null ? 0: this.userStatus.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java index 802a53f6528..4cfb876dd86 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java index 639c73d82fa..32c8cf811ee 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java index 30c93b34e77..1741cd98a42 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java index 753725d27dd..af3bff971a8 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java index c43979a8f6a..de82a75b556 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/async-scala/.swagger-codegen-ignore b/samples/client/petstore/async-scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/async-scala/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# 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/async-scala/LICENSE b/samples/client/petstore/async-scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/async-scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala index b918b0c55f8..97f1bb2ba62 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -1,8 +1,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import io.swagger.client.model.ApiResponse import java.io.File +import io.swagger.client.model.ApiResponse import com.wordnik.swagger.client._ import scala.concurrent.Future import collection.mutable @@ -19,8 +19,6 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->addPet") - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => process(reader.read(resp)) @@ -38,8 +36,10 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c val queryParams = new mutable.HashMap[String, String] val headerParams = new mutable.HashMap[String, String] - - headerParams += "api_key" -> apiKey.toString + apiKey match { + case Some(param) => headerParams += "api_key" -> param.toString + case _ => headerParams + } val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => @@ -56,10 +56,7 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c val headerParams = new mutable.HashMap[String, String] if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus") - - if (status != null) queryParams += "status" -> status.toString - - + queryParams += "status" -> status.toString val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => @@ -76,10 +73,7 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c val headerParams = new mutable.HashMap[String, String] if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags") - - if (tags != null) queryParams += "tags" -> tags.toString - - + queryParams += "tags" -> tags.toString val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => @@ -97,7 +91,6 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c val headerParams = new mutable.HashMap[String, String] - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => process(reader.read(resp)) @@ -114,8 +107,6 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->updatePet") - - val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => process(reader.read(resp)) @@ -135,7 +126,6 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c val headerParams = new mutable.HashMap[String, String] - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => process(reader.read(resp)) @@ -155,7 +145,6 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c val headerParams = new mutable.HashMap[String, String] - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => process(reader.read(resp)) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala index e17c641fcb2..22fb3706712 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -16,6 +16,7 @@ class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient val queryParams = new mutable.HashMap[String, String] val headerParams = new mutable.HashMap[String, String] + if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder") val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") @@ -33,7 +34,6 @@ class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient val headerParams = new mutable.HashMap[String, String] - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => process(reader.read(resp)) @@ -50,7 +50,6 @@ class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient val headerParams = new mutable.HashMap[String, String] - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => process(reader.read(resp)) @@ -67,8 +66,6 @@ class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient if (body == null) throw new Exception("Missing required parameter 'body' when calling StoreApi->placeOrder") - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => process(reader.read(resp)) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala index bf3294cb331..025c9f26925 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -17,8 +17,6 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUser") - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => process(reader.read(resp)) @@ -35,8 +33,6 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithArrayInput") - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => process(reader.read(resp)) @@ -53,8 +49,6 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithListInput") - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => process(reader.read(resp)) @@ -70,6 +64,7 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( val queryParams = new mutable.HashMap[String, String] val headerParams = new mutable.HashMap[String, String] + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser") val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") @@ -87,6 +82,7 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( val queryParams = new mutable.HashMap[String, String] val headerParams = new mutable.HashMap[String, String] + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName") val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") @@ -104,11 +100,12 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( val queryParams = new mutable.HashMap[String, String] val headerParams = new mutable.HashMap[String, String] - if (username != null) queryParams += "username" -> username.toString - - if (password != null) queryParams += "password" -> password.toString + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser") + if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser") + queryParams += "username" -> username.toString + queryParams += "password" -> password.toString val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => @@ -125,7 +122,6 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( val headerParams = new mutable.HashMap[String, String] - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") resFuture flatMap { resp => process(reader.read(resp)) @@ -142,9 +138,9 @@ class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient( val queryParams = new mutable.HashMap[String, String] val headerParams = new mutable.HashMap[String, String] - if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->updateUser") - + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser") + if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->updateUser") val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) resFuture flatMap { resp => diff --git a/samples/client/petstore/async-scala/src/test/scala/Test.scala b/samples/client/petstore/async-scala/src/test/scala/Test.scala index 749772a2718..796c96ca822 100644 --- a/samples/client/petstore/async-scala/src/test/scala/Test.scala +++ b/samples/client/petstore/async-scala/src/test/scala/Test.scala @@ -1,18 +1,17 @@ -import io.swagger.client._ -import io.swagger.client.api._ -import io.swagger.client.model._ - import java.net.URI +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import com.wordnik.swagger.client.SwaggerConfig +import io.swagger.client.SwaggerClient +import org.junit.runner.RunWith +import org.scalatest._ +import org.scalatest.junit.JUnitRunner + +import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success} -import org.scalatest._ -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FunSuite -import com.wordnik.swagger._ -com.wordnik.swagger.client @RunWith(classOf[JUnitRunner]) class SimpleTest extends FlatSpec with Matchers { diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj index a455838c8fc..96c1cf85fc2 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj @@ -90,7 +90,7 @@ (defn find-pets-by-tags-with-http-info "Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." ([] (find-pets-by-tags-with-http-info nil)) ([{:keys [tags ]}] (call-api "/pet/findByTags" :get @@ -104,7 +104,7 @@ (defn find-pets-by-tags "Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." ([] (find-pets-by-tags nil)) ([optional-params] (:data (find-pets-by-tags-with-http-info optional-params)))) diff --git a/samples/client/petstore/cpprest/.swagger-codegen-ignore b/samples/client/petstore/cpprest/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/cpprest/.swagger-codegen-ignore +++ b/samples/client/petstore/cpprest/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index 59cc503734c..b20eaf976b9 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -57,11 +57,11 @@ utility::string_t ApiClient::parameterToString(utility::string_t value) } utility::string_t ApiClient::parameterToString(int64_t value) { - return std::to_wstring(value); + return utility::conversions::to_string_t(std::to_string(value)); } utility::string_t ApiClient::parameterToString(int32_t value) { - return std::to_wstring(value); + return utility::conversions::to_string_t(std::to_string(value)); } pplx::task ApiClient::callApi( diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 54b0158eeb5..16e5ca125ae 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp index 61bf1a5e16d..e85f43d848f 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.cpp +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h index e9742d155fd..67cd2bf0178 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.h +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.cpp b/samples/client/petstore/cpprest/ApiException.cpp index 01ba891769e..8df3ce12400 100644 --- a/samples/client/petstore/cpprest/ApiException.cpp +++ b/samples/client/petstore/cpprest/ApiException.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h index beb2b5ea7e5..ef17912974d 100644 --- a/samples/client/petstore/cpprest/ApiException.h +++ b/samples/client/petstore/cpprest/ApiException.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.cpp b/samples/client/petstore/cpprest/HttpContent.cpp index a7a9b83aa59..2079be25aa4 100644 --- a/samples/client/petstore/cpprest/HttpContent.cpp +++ b/samples/client/petstore/cpprest/HttpContent.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h index 5db04412bd2..72545bf8ba5 100644 --- a/samples/client/petstore/cpprest/HttpContent.h +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -64,7 +64,7 @@ class HttpContent virtual void setData( std::shared_ptr value ); virtual void writeTo( std::ostream& stream ); - + protected: // NOTE: no utility::string_t here because those strings can only contain ascii utility::string_t m_ContentDisposition; diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h index 365109f3dab..80090afee4a 100644 --- a/samples/client/petstore/cpprest/IHttpBody.h +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/JsonBody.cpp b/samples/client/petstore/cpprest/JsonBody.cpp index f152a1e98ed..349bd6bfb1e 100644 --- a/samples/client/petstore/cpprest/JsonBody.cpp +++ b/samples/client/petstore/cpprest/JsonBody.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h index 7b139826e21..382004f6db5 100644 --- a/samples/client/petstore/cpprest/JsonBody.h +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp index 74e46b31faf..c8b64e27ea1 100644 --- a/samples/client/petstore/cpprest/ModelBase.cpp +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -330,7 +330,7 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr std::string str((std::istreambuf_iterator(*data.get())), std::istreambuf_iterator()); - return utility::conversions::to_utf16string(str); + return utility::conversions::to_string_t(str); } utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr val) { diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h index 8386a4ac97b..8514ec1ba8a 100644 --- a/samples/client/petstore/cpprest/ModelBase.h +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -64,7 +64,7 @@ class ModelBase static web::json::value toJson( int32_t value ); static web::json::value toJson( int64_t value ); static web::json::value toJson( double value ); - + static int64_t int64_tFromJson(web::json::value& val); static int32_t int32_tFromJson(web::json::value& val); static utility::string_t stringFromJson(web::json::value& val); diff --git a/samples/client/petstore/cpprest/MultipartFormData.cpp b/samples/client/petstore/cpprest/MultipartFormData.cpp index 9fffdf22b02..ca4ca814ff5 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.cpp +++ b/samples/client/petstore/cpprest/MultipartFormData.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h index 8fcd71ed011..01c1e7c0e8a 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.h +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index e573b9a08a6..9da8a514ef7 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -51,12 +51,6 @@ PetApi::~PetApi() 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")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); @@ -67,8 +61,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -82,7 +76,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->addPet does not produce any supported media type")); } @@ -150,7 +144,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -161,8 +155,8 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -183,8 +177,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -198,7 +192,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->deletePet does not produce any supported media type")); } @@ -256,7 +250,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -267,8 +261,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -288,8 +282,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -303,7 +297,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->findPetsByStatus does not produce any supported media type")); } @@ -357,7 +351,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -368,8 +362,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -415,8 +409,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -430,7 +424,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->findPetsByTags does not produce any supported media type")); } @@ -484,7 +478,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -495,8 +489,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -543,8 +537,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -558,7 +552,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->getPetById does not produce any supported media type")); } @@ -593,6 +587,8 @@ responseHttpContentTypes.insert( U("application/json") ); throw ApiException(415, U("PetApi->getPetById does not consume any supported media type")); } + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config // authentication (api_key) required { utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); @@ -617,7 +613,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -628,8 +624,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -657,12 +653,6 @@ responseHttpContentTypes.insert( U("application/json") ); 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")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); @@ -673,8 +663,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -688,7 +678,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->updatePet does not produce any supported media type")); } @@ -756,7 +746,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -767,15 +757,15 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); }); } -pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status) +pplx::task PetApi::updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status) { @@ -789,8 +779,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -804,7 +794,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->updatePetWithForm does not produce any supported media type")); } @@ -868,7 +858,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -879,15 +869,15 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); }); } -pplx::task> PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) +pplx::task PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) { @@ -902,6 +892,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -915,7 +906,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->uploadFile does not produce any supported media type")); } @@ -979,7 +970,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -990,31 +981,13 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { - std::shared_ptr result(new ApiResponse()); - - if(responseHttpContentType == U("application/json")) - { - web::json::value json = web::json::value::parse(response); - - result->fromJson(json); - } - // else if(responseHttpContentType == U("multipart/form-data")) - // { - // TODO multipart response parsing - // } - else - { - throw ApiException(500 - , U("error calling findPetsByStatus: unsupported response type")); - } - - return result; - }); + return void(); + }); } } diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index 0ee2bf64fe3..e3d1b40a3a8 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -36,7 +36,6 @@ #include "Pet.h" #include -#include "ApiResponse.h" #include "HttpContent.h" namespace io { @@ -57,7 +56,7 @@ class PetApi /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) pplx::task addPet(std::shared_ptr body); /// /// Deletes a pet @@ -73,7 +72,7 @@ class PetApi /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (optional, default to available) pplx::task>> findPetsByStatus(std::vector status); /// /// Finds Pets by tags @@ -81,15 +80,15 @@ class PetApi /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// - /// Tags to filter by + /// Tags to filter by (optional) pplx::task>> findPetsByTags(std::vector tags); /// /// Find pet by ID /// /// - /// Returns a single pet + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// - /// ID of pet to return + /// ID of pet that needs to be fetched pplx::task> getPetById(int64_t petId); /// /// Update an existing pet @@ -97,7 +96,7 @@ class PetApi /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) pplx::task updatePet(std::shared_ptr body); /// /// Updates a pet in the store with form data @@ -106,7 +105,7 @@ class PetApi /// /// /// ID of pet that needs to be updated/// Updated name of the pet (optional)/// Updated status of the pet (optional) - pplx::task updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status); + pplx::task updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status); /// /// uploads an image /// @@ -114,7 +113,7 @@ class PetApi /// /// /// ID of pet to update/// Additional data to pass to server (optional)/// file to upload (optional) - pplx::task> uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); + pplx::task uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); protected: std::shared_ptr m_ApiClient; diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp index dae3f04a985..406e6d0a909 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.cpp +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -62,8 +62,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -77,7 +77,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->deleteOrder does not produce any supported media type")); } @@ -128,7 +128,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -139,8 +139,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -161,6 +161,7 @@ pplx::task> StoreApi::getInventory() std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -174,7 +175,7 @@ pplx::task> StoreApi::getInventory() { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->getInventory does not produce any supported media type")); } @@ -229,7 +230,7 @@ pplx::task> StoreApi::getInventory() , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -240,8 +241,8 @@ pplx::task> StoreApi::getInventory() , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -272,7 +273,7 @@ pplx::task> StoreApi::getInventory() return result; }); } -pplx::task> StoreApi::getOrderById(int64_t orderId) +pplx::task> StoreApi::getOrderById(utility::string_t orderId) { @@ -286,8 +287,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -301,7 +302,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->getOrderById does not produce any supported media type")); } @@ -352,7 +353,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -363,8 +364,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -392,12 +393,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task> StoreApi::placeOrder(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling StoreApi->placeOrder")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/order"); @@ -408,8 +403,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -423,7 +418,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->placeOrder does not produce any supported media type")); } @@ -487,7 +482,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -498,8 +493,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 0b843e6e47b..e9c2ae6ca8c 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -73,14 +73,14 @@ class StoreApi /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - pplx::task> getOrderById(int64_t orderId); + pplx::task> getOrderById(utility::string_t orderId); /// /// Place an order for a pet /// /// /// /// - /// order placed for purchasing the pet + /// order placed for purchasing the pet (optional) pplx::task> placeOrder(std::shared_ptr body); protected: diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp index d376311036b..8259ef6ef9b 100644 --- a/samples/client/petstore/cpprest/api/UserApi.cpp +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -51,12 +51,6 @@ UserApi::~UserApi() 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")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user"); @@ -67,8 +61,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -82,7 +76,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->createUser does not produce any supported media type")); } @@ -146,7 +140,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -157,8 +151,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -178,8 +172,8 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -193,7 +187,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->createUsersWithArrayInput does not produce any supported media type")); } @@ -271,7 +265,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -282,8 +276,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -303,8 +297,8 @@ pplx::task UserApi::createUsersWithListInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -318,7 +312,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->createUsersWithListInput does not produce any supported media type")); } @@ -396,7 +390,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -407,8 +401,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -429,8 +423,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -444,7 +438,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->deleteUser does not produce any supported media type")); } @@ -495,7 +489,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -506,8 +500,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -528,8 +522,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -543,7 +537,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->getUserByName does not produce any supported media type")); } @@ -594,7 +588,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -605,8 +599,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -644,8 +638,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -659,7 +653,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->loginUser does not produce any supported media type")); } @@ -716,7 +710,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -727,8 +721,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -767,8 +761,8 @@ pplx::task UserApi::logoutUser() std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -782,7 +776,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->logoutUser does not produce any supported media type")); } @@ -829,7 +823,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -840,8 +834,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -851,12 +845,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task UserApi::updateUser(utility::string_t username, 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->updateUser")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/{username}"); @@ -868,8 +856,8 @@ 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( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -883,7 +871,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->updateUser does not produce any supported media type")); } @@ -951,7 +939,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -962,8 +950,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h index 5f6214f16ab..34425d67a77 100644 --- a/samples/client/petstore/cpprest/api/UserApi.h +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -56,7 +56,7 @@ class UserApi /// /// This can only be done by the logged in user. /// - /// Created user object + /// Created user object (optional) pplx::task createUser(std::shared_ptr body); /// /// Creates list of users with given input array @@ -64,7 +64,7 @@ class UserApi /// /// /// - /// List of user object + /// List of user object (optional) pplx::task createUsersWithArrayInput(std::vector> body); /// /// Creates list of users with given input array @@ -72,7 +72,7 @@ class UserApi /// /// /// - /// List of user object + /// List of user object (optional) pplx::task createUsersWithListInput(std::vector> body); /// /// Delete user @@ -96,7 +96,7 @@ class UserApi /// /// /// - /// The user name for login/// The password for login in clear text + /// The user name for login (optional)/// The password for login in clear text (optional) pplx::task loginUser(utility::string_t username, utility::string_t password); /// /// Logs out current logged in user session @@ -112,7 +112,7 @@ class UserApi /// /// This can only be done by the logged in user. /// - /// name that need to be deleted/// Updated user object + /// name that need to be deleted/// Updated user object (optional) pplx::task updateUser(utility::string_t username, std::shared_ptr body); protected: diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index 8221b52237a..f8cb2ec6bb4 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { Category::Category() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h index 63bf2907d31..690cf8bcf43 100644 --- a/samples/client/petstore/cpprest/model/Category.h +++ b/samples/client/petstore/cpprest/model/Category.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index 43105712525..0a2ffdec9fd 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,9 +33,9 @@ namespace model { Order::Order() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; - m_PetId = 0L; + m_PetId = 0; m_PetIdIsSet = false; m_Quantity = 0; m_QuantityIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h index 4af8f83d2d8..3c8bd62568f 100644 --- a/samples/client/petstore/cpprest/model/Order.h +++ b/samples/client/petstore/cpprest/model/Order.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index 578570305f7..3604e63659a 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { Pet::Pet() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_CategoryIsSet = false; m_Name = U(""); diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index 88a6fe19f7e..8127ed16132 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -34,10 +34,10 @@ #include "ModelBase.h" -#include "Category.h" +#include "Tag.h" #include +#include "Category.h" #include -#include "Tag.h" namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 3f51e7069c9..2cb33ba48cc 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { Tag::Tag() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h index 9a9381add81..ced6bdc5c4a 100644 --- a/samples/client/petstore/cpprest/model/Tag.h +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index 87ebe24916a..9beb9422a40 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { User::User() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_Username = U(""); m_UsernameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h index 48fdb7d60f6..8baaeaed353 100644 --- a/samples/client/petstore/cpprest/model/User.h +++ b/samples/client/petstore/cpprest/model/User.h @@ -1,9 +1,9 @@ /** * 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. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/csharp/SwaggerClient/.gitignore b/samples/client/petstore/csharp/SwaggerClient/.gitignore index 56fef626922..d3f4f7b6f55 100644 --- a/samples/client/petstore/csharp/SwaggerClient/.gitignore +++ b/samples/client/petstore/csharp/SwaggerClient/.gitignore @@ -147,39 +147,39 @@ UpgradeLog*.htm *.swp *.swo - # svn - .svn +# svn +.svn - # SQL Server files - **/App_Data/*.mdf - **/App_Data/*.ldf - **/App_Data/*.sdf +# SQL Server files +**/App_Data/*.mdf +**/App_Data/*.ldf +**/App_Data/*.sdf - #LightSwitch generated files - GeneratedArtifacts/ - _Pvt_Extensions/ - ModelManifest.xml +#LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml - # ========================= - # Windows detritus - # ========================= +# ========================= +# Windows detritus +# ========================= - # Windows image file caches - Thumbs.db - ehthumbs.db +# Windows image file caches +Thumbs.db +ehthumbs.db - # Folder config file - Desktop.ini +# Folder config file +Desktop.ini - # Recycle Bin used on file shares - $RECYCLE.BIN/ +# Recycle Bin used on file shares +$RECYCLE.BIN/ - # Mac desktop service store files - .DS_Store +# Mac desktop service store files +.DS_Store - # SASS Compiler cache - .sass-cache +# SASS Compiler cache +.sass-cache - # Visual Studio 2014 CTP - **/*.sln.ide +# Visual Studio 2014 CTP +**/*.sln.ide diff --git a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore index 61ed08d3455..7a6a67e36cc 100644 --- a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore +++ b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index d46556b3ff4..e6247e2a679 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{473916C4-D026-4063-8A3D-34BC255A0E7A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Debug|Any CPU.Build.0 = Debug|Any CPU -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Release|Any CPU.ActiveCfg = Release|Any CPU -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Release|Any CPU.Build.0 = Release|Any CPU +{473916C4-D026-4063-8A3D-34BC255A0E7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{473916C4-D026-4063-8A3D-34BC255A0E7A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{473916C4-D026-4063-8A3D-34BC255A0E7A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{473916C4-D026-4063-8A3D-34BC255A0E7A}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index e2d622cd13f..8b5ee417fbb 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -1,12 +1,11 @@ # 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 spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-06-23T12:09:14.609+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -14,8 +13,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - 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 +- [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 recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: ``` @@ -54,41 +53,33 @@ namespace Example { var apiInstance = new FakeApi(); - var number = 3.4; // decimal? | None - var _double = 1.2; // double? | None - var _string = _string_example; // string | None - var _byte = B; // byte[] | None - var integer = 56; // int? | None (optional) - var int32 = 56; // int? | None (optional) - var int64 = 789; // long? | None (optional) - var _float = 3.4; // float? | None (optional) - var binary = B; // byte[] | None (optional) - var date = 2013-10-20; // DateTime? | None (optional) - var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) - var password = password_example; // string | None (optional) + var body = new ModelClient(); // ModelClient | client model try { - // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + // To test \"client\" model + ModelClient result = apiInstance.TestClientModel(body); + Debug.WriteLine(result); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestClientModel: " + e.Message ); } } } } ``` + ## Documentation for API Endpoints All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**TestEnumQueryParameters**](docs/FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters *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 @@ -111,6 +102,7 @@ Class | Method | HTTP request | Description *UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + ## Documentation for Models - [Model.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) @@ -123,13 +115,16 @@ Class | Method | HTTP request | Description - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) - [Model.Dog](docs/Dog.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) @@ -143,13 +138,19 @@ Class | Method | HTTP request | Description ## Documentation for Authorization - + ### api_key - **Type**: API key - **API key parameter name**: api_key - **Location**: HTTP header + +### http_basic_test + +- **Type**: HTTP basic authentication + + ### petstore_auth - **Type**: OAuth diff --git a/samples/client/petstore/csharp/SwaggerClient/build.sh b/samples/client/petstore/csharp/SwaggerClient/build.sh index 25228f3cc36..b09ce1673fd 100644 --- a/samples/client/petstore/csharp/SwaggerClient/build.sh +++ b/samples/client/petstore/csharp/SwaggerClient/build.sh @@ -32,6 +32,7 @@ cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; echo "[INFO] Run 'mcs' to build bin/IO.Swagger.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ +System.ComponentModel.DataAnnotations.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/IO.Swagger.dll \ diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md index f8f285e08f4..37fb2788b77 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md @@ -6,7 +6,6 @@ Name | Type | Description | Notes **ArrayOfString** | **List<string>** | | [optional] **ArrayArrayOfInteger** | **List<List<long?>>** | | [optional] **ArrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] -**ArrayOfEnum** | **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/SwaggerClient/docs/EnumArrays.md b/samples/client/petstore/csharp/SwaggerClient/docs/EnumArrays.md new file mode 100644 index 00000000000..86fd208f8f8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/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/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index 9214eb84b3f..106daec81bf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -4,12 +4,74 @@ All URIs are relative to *http://petstore.swagger.io/v2* 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 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**TestEnumQueryParameters**](FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters +[**TestEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters + +# **TestClientModel** +> ModelClient TestClientModel (ModelClient body) + +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 _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) +> void TestEndpointParameters (decimal? number, double? _double, string 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) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -30,15 +92,20 @@ namespace Example 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 _string = _string_example; // string | None + var patternWithoutDelimiter = patternWithoutDelimiter_example; // string | None var _byte = B; // byte[] | None var integer = 56; // int? | None (optional) var int32 = 56; // int? | None (optional) var int64 = 789; // long? | None (optional) var _float = 3.4; // float? | None (optional) + var _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) @@ -47,7 +114,7 @@ namespace Example try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); } catch (Exception e) { @@ -64,12 +131,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **decimal?**| None | **_double** | **double?**| None | - **_string** | **string**| 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] @@ -81,7 +149,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -90,10 +158,11 @@ 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) -# **TestEnumQueryParameters** -> void TestEnumQueryParameters (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + +# **TestEnumParameters** +> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) -To test enum query parameters +To test enum parameters ### Example ```csharp @@ -105,24 +174,29 @@ using IO.Swagger.Model; namespace Example { - public class TestEnumQueryParametersExample + 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 = 3.4; // decimal? | Query parameter enum test (double) (optional) var enumQueryDouble = 1.2; // double? | Query parameter enum test (double) (optional) try { - // To test enum query parameters - apiInstance.TestEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + // To test enum parameters + apiInstance.TestEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestEnumQueryParameters: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestEnumParameters: " + e.Message ); } } } @@ -133,6 +207,11 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**List**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enumQueryInteger** | **decimal?**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/List.md b/samples/client/petstore/csharp/SwaggerClient/docs/List.md new file mode 100644 index 00000000000..d7555b7e7ac --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/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/SwaggerClient/docs/MapTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/MapTest.md new file mode 100644 index 00000000000..5c202aa336a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/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/SwaggerClient/docs/ModelClient.md b/samples/client/petstore/csharp/SwaggerClient/docs/ModelClient.md new file mode 100644 index 00000000000..9ecdc0e1141 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/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/SwaggerClient/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md index 837859e4b7e..de9223ef7a4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md @@ -14,6 +14,7 @@ Method | HTTP request | Description [**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + # **AddPet** > void AddPet (Pet body) @@ -37,7 +38,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + 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 @@ -77,6 +78,7 @@ void (empty response body) [[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) @@ -100,7 +102,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var petId = 789; // long? | Pet id to delete @@ -142,6 +144,7 @@ void (empty response body) [[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) @@ -165,7 +168,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var status = new List(); // List | Status values that need to be considered for filter @@ -206,6 +209,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **FindPetsByTags** > List FindPetsByTags (List tags) @@ -229,7 +233,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var tags = new List(); // List | Tags to filter by @@ -270,6 +274,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **GetPetById** > Pet GetPetById (long? petId) @@ -293,9 +298,9 @@ namespace Example { // Configure API key authorization: api_key - Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'Bearer'); + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet to return @@ -336,6 +341,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **UpdatePet** > void UpdatePet (Pet body) @@ -359,7 +365,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + 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 @@ -399,6 +405,7 @@ void (empty response body) [[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) @@ -422,7 +429,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet that needs to be updated @@ -466,6 +473,7 @@ void (empty response body) [[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) @@ -489,7 +497,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet to update diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md index a5d5ff0454d..24d03a779c5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md @@ -10,6 +10,7 @@ Method | HTTP request | Description [**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + # **DeleteOrder** > void DeleteOrder (string orderId) @@ -70,6 +71,7 @@ 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) + # **GetInventory** > Dictionary GetInventory () @@ -93,9 +95,9 @@ namespace Example { // Configure API key authorization: api_key - Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'Bearer'); + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); var apiInstance = new StoreApi(); @@ -132,6 +134,7 @@ This endpoint does not need any parameter. [[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) @@ -193,6 +196,7 @@ 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) + # **PlaceOrder** > Order PlaceOrder (Order body) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md index 65c22f9f072..e016a7a5e30 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md @@ -14,6 +14,7 @@ Method | HTTP request | Description [**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + # **CreateUser** > void CreateUser (User body) @@ -74,6 +75,7 @@ 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) + # **CreateUsersWithArrayInput** > void CreateUsersWithArrayInput (List body) @@ -134,6 +136,7 @@ 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) + # **CreateUsersWithListInput** > void CreateUsersWithListInput (List body) @@ -194,6 +197,7 @@ 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) + # **DeleteUser** > void DeleteUser (string username) @@ -254,6 +258,7 @@ 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) + # **GetUserByName** > User GetUserByName (string username) @@ -315,6 +320,7 @@ 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) + # **LoginUser** > string LoginUser (string username, string password) @@ -378,6 +384,7 @@ 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) + # **LogoutUser** > void LogoutUser () @@ -434,6 +441,7 @@ 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) + # **UpdateUser** > void UpdateUser (string username, User body) diff --git a/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh index e7032942787..602b9727d2c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh +++ b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh @@ -26,8 +26,8 @@ mozroots --import --sync mono nuget.exe install src/IO.Swagger.Test/packages.config -o packages echo "[INFO] Install NUnit runners via NuGet" -mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages +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.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll + 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/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 5660f132a37..72b7a3fc044 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -2,7 +2,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat new file mode 100644 index 00000000000..ae94b120d7b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat @@ -0,0 +1,28 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + +@echo off + +SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 + + +if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://nuget.org/nuget.exe', '.\nuget.exe')" +.\nuget.exe install src\IO.Swagger\packages.config -o packages + +if not exist ".\bin" mkdir bin + +copy packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll + +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh new file mode 100644 index 00000000000..b09ce1673fd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +frameworkVersion=net45 +netfx=${frameworkVersion#net} + +echo "[INFO] Target framework: ${frameworkVersion}" + +echo "[INFO] Download nuget and packages" +wget -nc https://nuget.org/nuget.exe; +mozroots --import --sync +mono nuget.exe install src/IO.Swagger/packages.config -o packages; + +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.8.0.3/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; + +echo "[INFO] Run 'mcs' to build bin/IO.Swagger.dll" +mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ +bin/RestSharp.dll,\ +System.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/SwaggerClientWithPropertyChanged/docs/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..ac4f9d10798 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Animal.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Animal.md new file mode 100644 index 00000000000..f461176159c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/AnimalFarm.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/AnimalFarm.md new file mode 100644 index 00000000000..4d1cccb0cef --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/ApiResponse.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ApiResponse.md new file mode 100644 index 00000000000..3e4b4c5e9cb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..3431d89edd0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/ArrayOfNumberOnly.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..9dc573663d6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/ArrayTest.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ArrayTest.md new file mode 100644 index 00000000000..37fb2788b77 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Cat.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Cat.md new file mode 100644 index 00000000000..a88425f4307 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Category.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Category.md new file mode 100644 index 00000000000..20b56b1728c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Dog.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Dog.md new file mode 100644 index 00000000000..c3ee6d927b4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/EnumArrays.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumArrays.md new file mode 100644 index 00000000000..86fd208f8f8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/EnumClass.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumClass.md new file mode 100644 index 00000000000..d936aad6f0b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/EnumTest.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumTest.md new file mode 100644 index 00000000000..f0f300021b5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumTest.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.EnumTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] +**EnumInteger** | **int?** | | [optional] +**EnumNumber** | **double?** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md new file mode 100644 index 00000000000..106daec81bf --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md @@ -0,0 +1,233 @@ +# IO.Swagger.Api.FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +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 + + + +# **TestClientModel** +> ModelClient TestClientModel (ModelClient body) + +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) + +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 = B; // byte[] | None + var integer = 56; // int? | None (optional) + var int32 = 56; // int? | None (optional) + var int64 = 789; // long? | None (optional) + var _float = 3.4; // float? | None (optional) + var _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) + + try + { + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + } + 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] + +### 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, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + +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 = 3.4; // decimal? | 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.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**List**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enumQueryInteger** | **decimal?**| 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**: 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/SwaggerClientWithPropertyChanged/docs/FormatTest.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FormatTest.md new file mode 100644 index 00000000000..1d366bd7cab --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/HasOnlyReadOnly.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..cf0190498b9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/List.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/List.md new file mode 100644 index 00000000000..d7555b7e7ac --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/MapTest.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/MapTest.md new file mode 100644 index 00000000000..5c202aa336a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e2c978f9ab1 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Model200Response.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Model200Response.md new file mode 100644 index 00000000000..cfaddb67027 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/ModelClient.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ModelClient.md new file mode 100644 index 00000000000..9ecdc0e1141 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/ModelReturn.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ModelReturn.md new file mode 100644 index 00000000000..9895ccde2b0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Name.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Name.md new file mode 100644 index 00000000000..678132c8e4e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/NumberOnly.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/NumberOnly.md new file mode 100644 index 00000000000..a156dc4e2fc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Order.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Order.md new file mode 100644 index 00000000000..32aeab388e5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/Pet.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Pet.md new file mode 100644 index 00000000000..e83933d1c60 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/PetApi.md new file mode 100644 index 00000000000..de9223ef7a4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/PetApi.md @@ -0,0 +1,544 @@ +# IO.Swagger.Api.PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **AddPet** +> void AddPet (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.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.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.ApiKey.Add("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("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/SwaggerClientWithPropertyChanged/docs/ReadOnlyFirst.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..b5f8d484869 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/SpecialModelName.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/SpecialModelName.md new file mode 100644 index 00000000000..ee1bc316835 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/StoreApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/StoreApi.md new file mode 100644 index 00000000000..24d03a779c5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/StoreApi.md @@ -0,0 +1,260 @@ +# IO.Swagger.Api.StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + + + +# **DeleteOrder** +> void DeleteOrder (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.ApiKey.Add("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("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/SwaggerClientWithPropertyChanged/docs/Tag.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/Tag.md new file mode 100644 index 00000000000..64c5e6bdc72 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/User.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/User.md new file mode 100644 index 00000000000..fbea33c48b9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/UserApi.md new file mode 100644 index 00000000000..e016a7a5e30 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/UserApi.md @@ -0,0 +1,506 @@ +# IO.Swagger.Api.UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user +[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +# **CreateUser** +> void CreateUser (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.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.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/SwaggerClientWithPropertyChanged/git_push.sh b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/git_push.sh new file mode 100644 index 00000000000..792320114fb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/mono_nunit_test.sh new file mode 100644 index 00000000000..602b9727d2c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/mono_nunit_test.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync + +echo "[INFO] remove bin/Debug/SwaggerClientTest.dll" +rm src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll 2> /dev/null + +echo "[INFO] install NUnit runners via NuGet" +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync +mono nuget.exe install src/IO.Swagger.Test/packages.config -o packages + +echo "[INFO] Install NUnit runners via NuGet" +mono nuget.exe install NUnit.Runners -Version 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/SwaggerClientWithPropertyChanged/nuget.exe b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/nuget.exe new file mode 100644 index 00000000000..324daa842c5 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/nuget.exe differ diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/FakeApiTests.cs new file mode 100644 index 00000000000..7922d898fdd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/FakeApiTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.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 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; + //instance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + + } + + /// + /// 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; + //decimal? enumQueryInteger = null; + //double? enumQueryDouble = null; + //instance.TestEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/PetApiTests.cs new file mode 100644 index 00000000000..a512676b08c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/PetApiTests.cs @@ -0,0 +1,182 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/StoreApiTests.cs new file mode 100644 index 00000000000..b7de1d862dc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/StoreApiTests.cs @@ -0,0 +1,128 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/UserApiTests.cs new file mode 100644 index 00000000000..ff5fdf17ad8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Api/UserApiTests.cs @@ -0,0 +1,178 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj new file mode 100644 index 00000000000..3a17bc59a9d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -0,0 +1,95 @@ + + + + + Debug + AnyCPU + {19F1DEBC-DE5E-4517-8062-F000CD499087} + Library + Properties + IO.Swagger.Test + IO.Swagger.Test + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + + + $(SolutionDir)\packages\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 + + + + + + + + + + + + {2A56AF87-B694-4558-9CBC-D85E740D4BFD} + IO.Swagger + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..bec025d5064 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing AdditionalPropertiesClass + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class AdditionalPropertiesClassTests + { + // 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AnimalFarmTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AnimalFarmTests.cs new file mode 100644 index 00000000000..6d0c4652992 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AnimalFarmTests.cs @@ -0,0 +1,82 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AnimalTests.cs new file mode 100644 index 00000000000..7f6b9a8b413 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/AnimalTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ApiResponseTests.cs new file mode 100644 index 00000000000..af03fac8071 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ApiResponseTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..18d4bf16cda --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..5a91f3736da --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayTestTests.cs new file mode 100644 index 00000000000..4c50d7166f5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ArrayTestTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ArrayTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ArrayTestTests + { + // 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/CatTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/CatTests.cs new file mode 100644 index 00000000000..b0a9047dde5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/CatTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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 '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' + } + /// + /// Test the property 'Declawed' + /// + [Test] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/CategoryTests.cs new file mode 100644 index 00000000000..f8940cdbc83 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/CategoryTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/DogTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/DogTests.cs new file mode 100644 index 00000000000..ba429c0b242 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/DogTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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 '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' + } + /// + /// Test the property 'Breed' + /// + [Test] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumArraysTests.cs new file mode 100644 index 00000000000..d6961ba49d0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumArraysTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumClassTests.cs new file mode 100644 index 00000000000..062799d7cd7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumClassTests.cs @@ -0,0 +1,82 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumTestTests.cs new file mode 100644 index 00000000000..6a1bb8620a2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/EnumTestTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/FormatTestTests.cs new file mode 100644 index 00000000000..9c4a16bea2e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/FormatTestTests.cs @@ -0,0 +1,186 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs new file mode 100644 index 00000000000..9d915a7ca86 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ListTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ListTests.cs new file mode 100644 index 00000000000..52037b2af00 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ListTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/MapTestTests.cs new file mode 100644 index 00000000000..f19089b6e03 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/MapTestTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..2c9be981907 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing MixedPropertiesAndAdditionalPropertiesClass + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class MixedPropertiesAndAdditionalPropertiesClassTests + { + // 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/Model200ResponseTests.cs new file mode 100644 index 00000000000..111603f66a6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/Model200ResponseTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ModelClientTests.cs new file mode 100644 index 00000000000..e1133467afc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ModelClientTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ModelReturnTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ModelReturnTests.cs new file mode 100644 index 00000000000..21265280525 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ModelReturnTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/NameTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/NameTests.cs new file mode 100644 index 00000000000..5e2cf85fc57 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/NameTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/NumberOnlyTests.cs new file mode 100644 index 00000000000..c7dd8269f69 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/NumberOnlyTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OrderTests.cs new file mode 100644 index 00000000000..d0e673a2142 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OrderTests.cs @@ -0,0 +1,130 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/PetTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/PetTests.cs new file mode 100644 index 00000000000..fc8fba31bb9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/PetTests.cs @@ -0,0 +1,130 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs new file mode 100644 index 00000000000..2d9da238b03 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ReadOnlyFirst + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ReadOnlyFirstTests + { + // 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs new file mode 100644 index 00000000000..9cac56054d0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/TagTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/TagTests.cs new file mode 100644 index 00000000000..eafbd6d80a2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/TagTests.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/UserTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/UserTests.cs new file mode 100644 index 00000000000..281273c60c2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/UserTests.cs @@ -0,0 +1,146 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing 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/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/packages.config b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/packages.config new file mode 100644 index 00000000000..9bb00f0fc4f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/packages.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs new file mode 100644 index 00000000000..f6d4c85a6ce --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs @@ -0,0 +1,938 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +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 + /// + /// To test \"client\" model + /// + /// + /// + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient TestClientModel (ModelClient body); + + /// + /// 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) + /// + 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); + + /// + /// 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) + /// 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); + /// + /// 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, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + + /// + /// 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, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + #endregion Synchronous Operations + #region Asynchronous Operations + /// + /// To test \"client\" model + /// + /// + /// + /// + /// Thrown when fails to make API call + /// client model + /// Task of ModelClient + System.Threading.Tasks.Task TestClientModelAsync (ModelClient body); + + /// + /// To test \"client\" model + /// + /// + /// + /// + /// Thrown when fails to make API call + /// client model + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> TestClientModelAsyncWithHttpInfo (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) + /// Task of void + System.Threading.Tasks.Task TestEndpointParametersAsync (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); + + /// + /// 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) + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (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); + /// + /// 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) + /// Task of void + System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + + /// + /// 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) + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + #endregion Asynchronous 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(new ApiClient(basePath)); + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public FakeApi(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath() + { + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do '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 Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + + /// + /// 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 + /// + /// 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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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))); + + } + + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Task of ModelClient + public async System.Threading.Tasks.Task TestClientModelAsync (ModelClient body) + { + ApiResponse localVarResponse = await TestClientModelAsyncWithHttpInfo(body); + return localVarResponse.Data; + + } + + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> TestClientModelAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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) await Configuration.ApiClient.CallApiAsync(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) + /// + 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) + { + TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// 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) + { + // 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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (integer != null) localVarFormParams.Add("integer", Configuration.ApiClient.ParameterToString(integer)); // form parameter + if (int32 != null) localVarFormParams.Add("int32", Configuration.ApiClient.ParameterToString(int32)); // form parameter + if (int64 != null) localVarFormParams.Add("int64", Configuration.ApiClient.ParameterToString(int64)); // form parameter + if (number != null) localVarFormParams.Add("number", Configuration.ApiClient.ParameterToString(number)); // form parameter + if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter + if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter + if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter + if (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 + + // 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); + } + + /// + /// 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) + /// Task of void + public async System.Threading.Tasks.Task TestEndpointParametersAsync (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) + { + await TestEndpointParametersAsyncWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (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) + { + // 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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (integer != null) localVarFormParams.Add("integer", Configuration.ApiClient.ParameterToString(integer)); // form parameter + if (int32 != null) localVarFormParams.Add("int32", Configuration.ApiClient.ParameterToString(int32)); // form parameter + if (int64 != null) localVarFormParams.Add("int64", Configuration.ApiClient.ParameterToString(int64)); // form parameter + if (number != null) localVarFormParams.Add("number", Configuration.ApiClient.ParameterToString(number)); // form parameter + if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter + if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter + if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter + if (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 + + // 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) await Configuration.ApiClient.CallApiAsync(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 + /// + /// 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, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + { + TestEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /// + /// 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, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + { + + var localVarPath = "/fake"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (enumQueryStringArray != null) localVarQueryParams.Add("enum_query_string_array", Configuration.ApiClient.ParameterToString(enumQueryStringArray)); // query parameter + if (enumQueryString != null) localVarQueryParams.Add("enum_query_string", Configuration.ApiClient.ParameterToString(enumQueryString)); // query parameter + if (enumQueryInteger != null) localVarQueryParams.Add("enum_query_integer", Configuration.ApiClient.ParameterToString(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); + } + + /// + /// 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) + /// Task of void + public async System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + { + await TestEnumParametersAsyncWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + } + + /// + /// 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) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + { + + var localVarPath = "/fake"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (enumQueryStringArray != null) localVarQueryParams.Add("enum_query_string_array", Configuration.ApiClient.ParameterToString(enumQueryStringArray)); // query parameter + if (enumQueryString != null) localVarQueryParams.Add("enum_query_string", Configuration.ApiClient.ParameterToString(enumQueryString)); // query parameter + if (enumQueryInteger != null) localVarQueryParams.Add("enum_query_integer", Configuration.ApiClient.ParameterToString(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) await Configuration.ApiClient.CallApiAsync(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); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs new file mode 100644 index 00000000000..fdf4b752799 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs @@ -0,0 +1,1809 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +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 + #region Asynchronous 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 + /// Task of void + System.Threading.Tasks.Task AddPetAsync (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 + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetAsyncWithHttpInfo (Pet body); + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Task of void + System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey = null); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Task of ApiResponse + System.Threading.Tasks.Task> DeletePetAsyncWithHttpInfo (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 + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByStatusAsync (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 + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (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 + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByTagsAsync (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 + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByTagsAsyncWithHttpInfo (List tags); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Task of Pet + System.Threading.Tasks.Task GetPetByIdAsync (long? petId); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Task of ApiResponse (Pet) + System.Threading.Tasks.Task> GetPetByIdAsyncWithHttpInfo (long? petId); + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Task of void + System.Threading.Tasks.Task UpdatePetAsync (Pet body); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetAsyncWithHttpInfo (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) + /// Task of void + System.Threading.Tasks.Task UpdatePetWithFormAsync (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) + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetWithFormAsyncWithHttpInfo (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) + /// Task of ApiResponse + System.Threading.Tasks.Task UploadFileAsync (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) + /// Task of ApiResponse (ApiResponse) + System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, System.IO.Stream file = null); + #endregion Asynchronous 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(new ApiClient(basePath)); + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public 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; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath() + { + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do '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 Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + + /// + /// 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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Task of void + public async System.Threading.Tasks.Task AddPetAsync (Pet body) + { + await AddPetAsyncWithHttpInfo(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 + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Task of void + public async System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey = null) + { + await DeletePetAsyncWithHttpInfo(petId, apiKey); + + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeletePetAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (status != null) localVarQueryParams.Add("status", Configuration.ApiClient.ParameterToString(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 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 + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List status) + { + ApiResponse> localVarResponse = await FindPetsByStatusAsyncWithHttpInfo(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 + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (status != null) localVarQueryParams.Add("status", Configuration.ApiClient.ParameterToString(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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (tags != null) localVarQueryParams.Add("tags", Configuration.ApiClient.ParameterToString(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))); + + } + + /// + /// 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 + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags) + { + ApiResponse> localVarResponse = await FindPetsByTagsAsyncWithHttpInfo(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 + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByTagsAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (tags != null) localVarQueryParams.Add("tags", Configuration.ApiClient.ParameterToString(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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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))); + + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Task of Pet + public async System.Threading.Tasks.Task GetPetByIdAsync (long? petId) + { + ApiResponse localVarResponse = await GetPetByIdAsyncWithHttpInfo(petId); + return localVarResponse.Data; + + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Task of ApiResponse (Pet) + public async System.Threading.Tasks.Task> GetPetByIdAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Task of void + public async System.Threading.Tasks.Task UpdatePetAsync (Pet body) + { + await UpdatePetAsyncWithHttpInfo(body); + + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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); + } + + /// + /// 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) + /// Task of void + public async System.Threading.Tasks.Task UpdatePetWithFormAsync (long? petId, string name = null, string status = null) + { + await UpdatePetWithFormAsyncWithHttpInfo(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) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetWithFormAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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))); + + } + + /// + /// 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) + /// Task of ApiResponse + public async System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata = null, System.IO.Stream file = null) + { + ApiResponse localVarResponse = await UploadFileAsyncWithHttpInfo(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) + /// Task of ApiResponse (ApiResponse) + public async System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "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); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + 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) await Configuration.ApiClient.CallApiAsync(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/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs new file mode 100644 index 00000000000..668bb7819b4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs @@ -0,0 +1,899 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +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 + #region Asynchronous 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 + /// Task of void + System.Threading.Tasks.Task DeleteOrderAsync (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 + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteOrderAsyncWithHttpInfo (string orderId); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of Dictionary<string, int?> + System.Threading.Tasks.Task> GetInventoryAsync (); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of ApiResponse (Dictionary<string, int?>) + System.Threading.Tasks.Task>> GetInventoryAsyncWithHttpInfo (); + /// + /// 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 + /// Task of Order + System.Threading.Tasks.Task GetOrderByIdAsync (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 + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> GetOrderByIdAsyncWithHttpInfo (long? orderId); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Task of Order + System.Threading.Tasks.Task PlaceOrderAsync (Order body); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> PlaceOrderAsyncWithHttpInfo (Order body); + #endregion Asynchronous 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(new ApiClient(basePath)); + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public 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; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath() + { + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do '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 Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + + /// + /// 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/{orderId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (orderId != null) localVarPathParams.Add("orderId", 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); + } + + /// + /// 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 + /// Task of void + public async System.Threading.Tasks.Task DeleteOrderAsync (string orderId) + { + await DeleteOrderAsyncWithHttpInfo(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 + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteOrderAsyncWithHttpInfo (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/{orderId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (orderId != null) localVarPathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + + // 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))); + + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of Dictionary<string, int?> + public async System.Threading.Tasks.Task> GetInventoryAsync () + { + ApiResponse> localVarResponse = await GetInventoryAsyncWithHttpInfo(); + return localVarResponse.Data; + + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of ApiResponse (Dictionary<string, int?>) + public async System.Threading.Tasks.Task>> GetInventoryAsyncWithHttpInfo () + { + + var localVarPath = "/store/inventory"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + + // 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) await Configuration.ApiClient.CallApiAsync(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/{orderId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (orderId != null) localVarPathParams.Add("orderId", 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))); + + } + + /// + /// 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 + /// Task of Order + public async System.Threading.Tasks.Task GetOrderByIdAsync (long? orderId) + { + ApiResponse localVarResponse = await GetOrderByIdAsyncWithHttpInfo(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 + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> GetOrderByIdAsyncWithHttpInfo (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/{orderId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (orderId != null) localVarPathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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))); + + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Task of Order + public async System.Threading.Tasks.Task PlaceOrderAsync (Order body) + { + ApiResponse localVarResponse = await PlaceOrderAsyncWithHttpInfo(body); + return localVarResponse.Data; + + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> PlaceOrderAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs new file mode 100644 index 00000000000..1865ec1631d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs @@ -0,0 +1,1694 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +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 + #region Asynchronous Operations + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Task of void + System.Threading.Tasks.Task CreateUserAsync (User body); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUserAsyncWithHttpInfo (User body); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of void + System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithArrayInputAsyncWithHttpInfo (List body); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of void + System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithListInputAsyncWithHttpInfo (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 + /// Task of void + System.Threading.Tasks.Task DeleteUserAsync (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 + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteUserAsyncWithHttpInfo (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. + /// Task of User + System.Threading.Tasks.Task GetUserByNameAsync (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. + /// Task of ApiResponse (User) + System.Threading.Tasks.Task> GetUserByNameAsyncWithHttpInfo (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 + /// Task of string + System.Threading.Tasks.Task LoginUserAsync (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 + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> LoginUserAsyncWithHttpInfo (string username, string password); + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Task of void + System.Threading.Tasks.Task LogoutUserAsync (); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Task of ApiResponse + System.Threading.Tasks.Task> LogoutUserAsyncWithHttpInfo (); + /// + /// 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 + /// Task of void + System.Threading.Tasks.Task UpdateUserAsync (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 + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdateUserAsyncWithHttpInfo (string username, User body); + #endregion Asynchronous 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(new ApiClient(basePath)); + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public 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; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath() + { + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do '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 Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + + /// + /// 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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Task of void + public async System.Threading.Tasks.Task CreateUserAsync (User body) + { + await CreateUserAsyncWithHttpInfo(body); + + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUserAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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 + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body) + { + await CreateUsersWithArrayInputAsyncWithHttpInfo(body); + + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithArrayInputAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body) + { + await CreateUsersWithListInputAsyncWithHttpInfo(body); + + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithListInputAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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); + } + + /// + /// 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 + /// Task of void + public async System.Threading.Tasks.Task DeleteUserAsync (string username) + { + await DeleteUserAsyncWithHttpInfo(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 + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteUserAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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))); + + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Task of User + public async System.Threading.Tasks.Task GetUserByNameAsync (string username) + { + ApiResponse localVarResponse = await GetUserByNameAsyncWithHttpInfo(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. + /// Task of ApiResponse (User) + public async System.Threading.Tasks.Task> GetUserByNameAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (username != null) localVarQueryParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // query parameter + if (password != null) localVarQueryParams.Add("password", Configuration.ApiClient.ParameterToString(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 user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Task of string + public async System.Threading.Tasks.Task LoginUserAsync (string username, string password) + { + ApiResponse localVarResponse = await LoginUserAsyncWithHttpInfo(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 + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> LoginUserAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (username != null) localVarQueryParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // query parameter + if (password != null) localVarQueryParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // query parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + + + // 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); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Task of void + public async System.Threading.Tasks.Task LogoutUserAsync () + { + await LogoutUserAsyncWithHttpInfo(); + + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Task of ApiResponse + public async System.Threading.Tasks.Task> LogoutUserAsyncWithHttpInfo () + { + + var localVarPath = "/user/logout"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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); + } + + /// + /// 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 + /// Task of void + public async System.Threading.Tasks.Task UpdateUserAsync (string username, User body) + { + await UpdateUserAsyncWithHttpInfo(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 + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdateUserAsyncWithHttpInfo (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 Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (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) await Configuration.ApiClient.CallApiAsync(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/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs new file mode 100644 index 00000000000..5aaf146d69e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs @@ -0,0 +1,494 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +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 and base path (http://petstore.swagger.io/v2). + /// + public ApiClient() + { + Configuration = Configuration.Default; + RestClient = new RestClient("http://petstore.swagger.io/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default base path (http://petstore.swagger.io/v2). + /// + /// An instance of Configuration. + public ApiClient(Configuration config = null) + { + if (config == null) + Configuration = Configuration.Default; + else + Configuration = config; + + RestClient = new RestClient("http://petstore.swagger.io/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. + /// + /// The base path. + public ApiClient(String basePath = "http://petstore.swagger.io/v2") + { + if (String.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + RestClient = new RestClient(basePath); + Configuration = 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 the Configuration. + /// + /// An instance of the Configuration. + public Configuration 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, Dictionary 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 + { + if (postBody.GetType() == typeof(String)) + { + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + } + else if (postBody.GetType() == typeof(byte[])) + { + 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, Dictionary 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; + } + /// + /// Makes the asynchronous HTTP request. + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Path parameters. + /// Content type. + /// The Task instance. + public async System.Threading.Tasks.Task CallApiAsync( + String path, RestSharp.Method method, Dictionary 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); + InterceptRequest(request); + var response = await RestClient.ExecuteTaskAsync(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; + } + + 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); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON 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 null; + + if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + 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. + /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast + /// + /// Object to be casted + /// Target type + /// Casted object + public static dynamic ConvertType(dynamic source, Type dest) + { + return Convert.ChangeType(source, dest); + } + + /// + /// Convert stream to byte array + /// Credit/Ref: http://stackoverflow.com/a/221941/677735 + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream input) + { + byte[] buffer = new byte[16*1024]; + using (MemoryStream ms = new MemoryStream()) + { + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + 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; + } + } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.cs new file mode 100644 index 00000000000..1afc1529a75 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; + +namespace IO.Swagger.Client +{ + /// + /// 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 dynamic 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, dynamic errorContent = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs new file mode 100644 index 00000000000..03c64ab42e2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs @@ -0,0 +1,66 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; + +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/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs new file mode 100644 index 00000000000..12f87d6e6fa --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs @@ -0,0 +1,338 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Reflection; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace IO.Swagger.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration + { + /// + /// Initializes a new instance of the Configuration 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 + public Configuration(ApiClient apiClient = null, + Dictionary defaultHeader = null, + string username = null, + string password = null, + string accessToken = null, + Dictionary apiKey = null, + Dictionary apiKeyPrefix = null, + string tempFolderPath = null, + string dateTimeFormat = null, + int timeout = 100000, + string userAgent = "Swagger-Codegen/1.0.0/csharp" + ) + { + setApiClientUsingDefault(apiClient); + + Username = username; + Password = password; + AccessToken = accessToken; + UserAgent = userAgent; + + if (defaultHeader != null) + DefaultHeader = defaultHeader; + if (apiKey != null) + ApiKey = apiKey; + if (apiKeyPrefix != null) + ApiKeyPrefix = apiKeyPrefix; + + TempFolderPath = tempFolderPath; + DateTimeFormat = dateTimeFormat; + Timeout = timeout; + } + + /// + /// Initializes a new instance of the Configuration class. + /// + /// Api client. + public Configuration(ApiClient apiClient) + { + setApiClientUsingDefault(apiClient); + } + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static Configuration Default = new Configuration(); + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + int status = (int) response.StatusCode; + if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); + if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); + return null; + }; + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + /// Timeout. + public int Timeout + { + get { return ApiClient.RestClient.Timeout; } + + set + { + if (ApiClient != null) + ApiClient.RestClient.Timeout = value; + } + } + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The API client. + public ApiClient ApiClient; + + /// + /// Set the ApiClient using Default or ApiClient instance. + /// + /// An instance of ApiClient. + /// + public void setApiClientUsingDefault (ApiClient apiClient = null) + { + if (apiClient == null) + { + if (Default != null && Default.ApiClient == null) + Default.ApiClient = new ApiClient(); + + ApiClient = Default != null ? Default.ApiClient : new ApiClient(); + } + else + { + if (Default != null && Default.ApiClient == null) + Default.ApiClient = apiClient; + + ApiClient = apiClient; + } + } + + private Dictionary _defaultHeaderMap = new Dictionary(); + + /// + /// Gets or sets the default header. + /// + public Dictionary DefaultHeader + { + get { return _defaultHeaderMap; } + + set + { + _defaultHeaderMap = value; + } + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + _defaultHeaderMap[key] = value; + } + + /// + /// 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; + } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public String UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public String Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public String Password { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// The access token. + public String AccessToken { get; set; } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public Dictionary ApiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + public Dictionary ApiKeyPrefix = new Dictionary(); + + /// + /// Get 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; + } + + private string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public String TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (String.IsNullOrEmpty(value)) + { + _tempFolderPath = value; + 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; + } + } + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// 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 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; + } + } + + /// + /// Returns a string with essential information for debugging. + /// + public static String ToDebugReport() + { + String report = "C# SDK (IO.Swagger) Debug Report:\n"; + report += " OS: " + Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + Assembly + .GetExecutingAssembly() + .GetReferencedAssemblies() + .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..129e591f8a7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs @@ -0,0 +1,36 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using System; +using RestSharp; + +namespace IO.Swagger.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IRestResponse response); +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs new file mode 100644 index 00000000000..845e6a49e9b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs @@ -0,0 +1,54 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; + +namespace IO.Swagger.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + Configuration Configuration {get; set;} + + /// + /// Gets the base path of the API client. + /// + /// The base path + String GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/FodyWeavers.xml b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/FodyWeavers.xml new file mode 100644 index 00000000000..da017fcbf60 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/FodyWeavers.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj new file mode 100644 index 00000000000..7827cb719dc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj @@ -0,0 +1,88 @@ + + + + + Debug + AnyCPU + {2A56AF87-B694-4558-9CBC-D85E740D4BFD} + Library + Properties + IO.Swagger + IO.Swagger + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + + + ..\..\packages\PropertyChanged.Fody.1.51.3\Lib\portable-net4+sl4+wp8+win8+wpa81+MonoAndroid16+MonoTouch40\PropertyChanged.dll + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs new file mode 100644 index 00000000000..875e2eed2ce --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// AdditionalPropertiesClass + /// + [DataContract] + [ImplementPropertyChanged] + public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// MapProperty. + /// MapOfMapProperty. + public AdditionalPropertiesClass(Dictionary MapProperty = null, Dictionary> MapOfMapProperty = null) + { + this.MapProperty = MapProperty; + this.MapOfMapProperty = MapOfMapProperty; + } + + /// + /// Gets or Sets MapProperty + /// + [DataMember(Name="map_property", EmitDefaultValue=false)] + public Dictionary MapProperty { get; set; } + /// + /// Gets or Sets MapOfMapProperty + /// + [DataMember(Name="map_of_map_property", EmitDefaultValue=false)] + public Dictionary> MapOfMapProperty { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as AdditionalPropertiesClass); + } + + /// + /// Returns true if AdditionalPropertiesClass instances are equal + /// + /// Instance of AdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(AdditionalPropertiesClass other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.MapProperty == other.MapProperty || + this.MapProperty != null && + this.MapProperty.SequenceEqual(other.MapProperty) + ) && + ( + this.MapOfMapProperty == other.MapOfMapProperty || + this.MapOfMapProperty != null && + this.MapOfMapProperty.SequenceEqual(other.MapOfMapProperty) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.MapProperty != null) + hash = hash * 59 + this.MapProperty.GetHashCode(); + if (this.MapOfMapProperty != null) + hash = hash * 59 + this.MapOfMapProperty.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs new file mode 100644 index 00000000000..97fee42a3a4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs @@ -0,0 +1,185 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Animal + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, string Color = null) + { + // 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 string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Animal); + } + + /// + /// Returns true if Animal instances are equal + /// + /// Instance of Animal to be compared + /// Boolean + public bool Equals(Animal other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ClassName == other.ClassName || + this.ClassName != null && + this.ClassName.Equals(other.ClassName) + ) && + ( + this.Color == other.Color || + this.Color != null && + this.Color.Equals(other.Color) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ClassName != null) + hash = hash * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hash = hash * 59 + this.Color.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs new file mode 100644 index 00000000000..6febf5ed135 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs @@ -0,0 +1,135 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// AnimalFarm + /// + [DataContract] + [ImplementPropertyChanged] + public partial class AnimalFarm : List, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public AnimalFarm() + { + } + + /// + /// 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("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public new string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as AnimalFarm); + } + + /// + /// Returns true if AnimalFarm instances are equal + /// + /// Instance of AnimalFarm to be compared + /// Boolean + public bool Equals(AnimalFarm other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return false; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs new file mode 100644 index 00000000000..ebbcad265c4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs @@ -0,0 +1,179 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// ApiResponse + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ApiResponse : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Code. + /// Type. + /// Message. + public ApiResponse(int? Code = null, string Type = null, string Message = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ApiResponse); + } + + /// + /// Returns true if ApiResponse instances are equal + /// + /// Instance of ApiResponse to be compared + /// Boolean + public bool Equals(ApiResponse other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Code == other.Code || + this.Code != null && + this.Code.Equals(other.Code) + ) && + ( + this.Type == other.Type || + this.Type != null && + this.Type.Equals(other.Type) + ) && + ( + this.Message == other.Message || + this.Message != null && + this.Message.Equals(other.Message) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Code != null) + hash = hash * 59 + this.Code.GetHashCode(); + if (this.Type != null) + hash = hash * 59 + this.Type.GetHashCode(); + if (this.Message != null) + hash = hash * 59 + this.Message.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs new file mode 100644 index 00000000000..ac5ac025933 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// ArrayOfArrayOfNumberOnly + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayArrayNumber. + public ArrayOfArrayOfNumberOnly(List> ArrayArrayNumber = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ArrayOfArrayOfNumberOnly); + } + + /// + /// Returns true if ArrayOfArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfArrayOfNumberOnly other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ArrayArrayNumber == other.ArrayArrayNumber || + this.ArrayArrayNumber != null && + this.ArrayArrayNumber.SequenceEqual(other.ArrayArrayNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ArrayArrayNumber != null) + hash = hash * 59 + this.ArrayArrayNumber.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs new file mode 100644 index 00000000000..7aa16298467 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// ArrayOfNumberOnly + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayNumber. + public ArrayOfNumberOnly(List ArrayNumber = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ArrayOfNumberOnly); + } + + /// + /// Returns true if ArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfNumberOnly other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ArrayNumber == other.ArrayNumber || + this.ArrayNumber != null && + this.ArrayNumber.SequenceEqual(other.ArrayNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ArrayNumber != null) + hash = hash * 59 + this.ArrayNumber.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs new file mode 100644 index 00000000000..b13880edacd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs @@ -0,0 +1,179 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// ArrayTest + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ArrayTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayOfString. + /// ArrayArrayOfInteger. + /// ArrayArrayOfModel. + public ArrayTest(List ArrayOfString = null, List> ArrayArrayOfInteger = null, List> ArrayArrayOfModel = null) + { + this.ArrayOfString = ArrayOfString; + this.ArrayArrayOfInteger = ArrayArrayOfInteger; + this.ArrayArrayOfModel = ArrayArrayOfModel; + } + + /// + /// Gets or Sets ArrayOfString + /// + [DataMember(Name="array_of_string", EmitDefaultValue=false)] + public List ArrayOfString { get; set; } + /// + /// Gets or Sets ArrayArrayOfInteger + /// + [DataMember(Name="array_array_of_integer", EmitDefaultValue=false)] + public List> ArrayArrayOfInteger { get; set; } + /// + /// Gets or Sets ArrayArrayOfModel + /// + [DataMember(Name="array_array_of_model", EmitDefaultValue=false)] + public List> ArrayArrayOfModel { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ArrayTest {\n"); + sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); + sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); + sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ArrayTest); + } + + /// + /// Returns true if ArrayTest instances are equal + /// + /// Instance of ArrayTest to be compared + /// Boolean + public bool Equals(ArrayTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ArrayOfString == other.ArrayOfString || + this.ArrayOfString != null && + this.ArrayOfString.SequenceEqual(other.ArrayOfString) + ) && + ( + this.ArrayArrayOfInteger == other.ArrayArrayOfInteger || + this.ArrayArrayOfInteger != null && + this.ArrayArrayOfInteger.SequenceEqual(other.ArrayArrayOfInteger) + ) && + ( + this.ArrayArrayOfModel == other.ArrayArrayOfModel || + this.ArrayArrayOfModel != null && + this.ArrayArrayOfModel.SequenceEqual(other.ArrayArrayOfModel) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ArrayOfString != null) + hash = hash * 59 + this.ArrayOfString.GetHashCode(); + if (this.ArrayArrayOfInteger != null) + hash = hash * 59 + this.ArrayArrayOfInteger.GetHashCode(); + if (this.ArrayArrayOfModel != null) + hash = hash * 59 + this.ArrayArrayOfModel.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs new file mode 100644 index 00000000000..1120e2faf92 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs @@ -0,0 +1,200 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Cat + /// + [DataContract] + [ImplementPropertyChanged] + public partial class Cat : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() { } + /// + /// Initializes a new instance of the class. + /// + /// ClassName (required). + /// Color (default to "red"). + /// Declawed. + public Cat(string ClassName = null, string Color = null, bool? Declawed = null) + { + // to ensure "ClassName" is required (not null) + if (ClassName == null) + { + throw new InvalidDataException("ClassName is a required property for Cat 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; + } + this.Declawed = Declawed; + } + + /// + /// 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; } + /// + /// 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(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Color: ").Append(Color).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 new string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Cat); + } + + /// + /// Returns true if Cat instances are equal + /// + /// Instance of Cat to be compared + /// Boolean + public bool Equals(Cat other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ClassName == other.ClassName || + this.ClassName != null && + this.ClassName.Equals(other.ClassName) + ) && + ( + this.Color == other.Color || + this.Color != null && + this.Color.Equals(other.Color) + ) && + ( + this.Declawed == other.Declawed || + this.Declawed != null && + this.Declawed.Equals(other.Declawed) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ClassName != null) + hash = hash * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hash = hash * 59 + this.Color.GetHashCode(); + if (this.Declawed != null) + hash = hash * 59 + this.Declawed.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs new file mode 100644 index 00000000000..27e980bc721 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Category + /// + [DataContract] + [ImplementPropertyChanged] + public partial class Category : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// Name. + public Category(long? Id = null, string Name = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Category); + } + + /// + /// Returns true if Category instances are equal + /// + /// Instance of Category to be compared + /// Boolean + public bool Equals(Category other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Id == other.Id || + this.Id != null && + this.Id.Equals(other.Id) + ) && + ( + this.Name == other.Name || + this.Name != null && + this.Name.Equals(other.Name) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Id != null) + hash = hash * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hash = hash * 59 + this.Name.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs new file mode 100644 index 00000000000..8e834c85e6a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs @@ -0,0 +1,200 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Dog + /// + [DataContract] + [ImplementPropertyChanged] + public partial class Dog : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() { } + /// + /// Initializes a new instance of the class. + /// + /// ClassName (required). + /// Color (default to "red"). + /// Breed. + public Dog(string ClassName = null, string Color = null, string Breed = null) + { + // to ensure "ClassName" is required (not null) + if (ClassName == null) + { + throw new InvalidDataException("ClassName is a required property for Dog 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; + } + this.Breed = Breed; + } + + /// + /// 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; } + /// + /// 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(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Color: ").Append(Color).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 new string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Dog); + } + + /// + /// Returns true if Dog instances are equal + /// + /// Instance of Dog to be compared + /// Boolean + public bool Equals(Dog other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.ClassName == other.ClassName || + this.ClassName != null && + this.ClassName.Equals(other.ClassName) + ) && + ( + this.Color == other.Color || + this.Color != null && + this.Color.Equals(other.Color) + ) && + ( + this.Breed == other.Breed || + this.Breed != null && + this.Breed.Equals(other.Breed) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.ClassName != null) + hash = hash * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hash = hash * 59 + this.Color.GetHashCode(); + if (this.Breed != null) + hash = hash * 59 + this.Breed.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs new file mode 100644 index 00000000000..faa2f74a1c6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// EnumArrays + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, List ArrayEnum = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as EnumArrays); + } + + /// + /// Returns true if EnumArrays instances are equal + /// + /// Instance of EnumArrays to be compared + /// Boolean + public bool Equals(EnumArrays other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.JustSymbol == other.JustSymbol || + this.JustSymbol != null && + this.JustSymbol.Equals(other.JustSymbol) + ) && + ( + this.ArrayEnum == other.ArrayEnum || + this.ArrayEnum != null && + this.ArrayEnum.SequenceEqual(other.ArrayEnum) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.JustSymbol != null) + hash = hash * 59 + this.JustSymbol.GetHashCode(); + if (this.ArrayEnum != null) + hash = hash * 59 + this.ArrayEnum.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs new file mode 100644 index 00000000000..60432e1d3bf --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs @@ -0,0 +1,66 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +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/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs new file mode 100644 index 00000000000..b2c9e8e8e2e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs @@ -0,0 +1,239 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// EnumTest + /// + [DataContract] + [ImplementPropertyChanged] + 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 + } + + /// + /// Gets or Sets EnumInteger + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumIntegerEnum + { + + /// + /// Enum NUMBER_1 for 1 + /// + [EnumMember(Value = "1")] + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for -1 + /// + [EnumMember(Value = "-1")] + NUMBER_MINUS_1 = -1 + } + + /// + /// Gets or Sets EnumNumber + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumNumberEnum + { + + /// + /// Enum NUMBER_1_DOT_1 for 1.1 + /// + [EnumMember(Value = "1.1")] + NUMBER_1_DOT_1, + + /// + /// Enum NUMBER_MINUS_1_DOT_2 for -1.2 + /// + [EnumMember(Value = "-1.2")] + NUMBER_MINUS_1_DOT_2 + } + + /// + /// Gets or Sets EnumString + /// + [DataMember(Name="enum_string", EmitDefaultValue=false)] + public EnumStringEnum? EnumString { get; set; } + /// + /// Gets or Sets EnumInteger + /// + [DataMember(Name="enum_integer", EmitDefaultValue=false)] + public EnumIntegerEnum? EnumInteger { get; set; } + /// + /// Gets or Sets EnumNumber + /// + [DataMember(Name="enum_number", EmitDefaultValue=false)] + public EnumNumberEnum? EnumNumber { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// EnumString. + /// EnumInteger. + /// EnumNumber. + public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null) + { + this.EnumString = EnumString; + this.EnumInteger = EnumInteger; + this.EnumNumber = EnumNumber; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class EnumTest {\n"); + sb.Append(" EnumString: ").Append(EnumString).Append("\n"); + sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); + sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as EnumTest); + } + + /// + /// Returns true if EnumTest instances are equal + /// + /// Instance of EnumTest to be compared + /// Boolean + public bool Equals(EnumTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.EnumString == other.EnumString || + this.EnumString != null && + this.EnumString.Equals(other.EnumString) + ) && + ( + this.EnumInteger == other.EnumInteger || + this.EnumInteger != null && + this.EnumInteger.Equals(other.EnumInteger) + ) && + ( + this.EnumNumber == other.EnumNumber || + this.EnumNumber != null && + this.EnumNumber.Equals(other.EnumNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.EnumString != null) + hash = hash * 59 + this.EnumString.GetHashCode(); + if (this.EnumInteger != null) + hash = hash * 59 + this.EnumInteger.GetHashCode(); + if (this.EnumNumber != null) + hash = hash * 59 + this.EnumNumber.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs new file mode 100644 index 00000000000..e00fdf2f745 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs @@ -0,0 +1,445 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// FormatTest + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, int? Int32 = null, long? Int64 = null, decimal? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) + { + // to ensure "Number" is required (not null) + if (Number == null) + { + 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)] + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as FormatTest); + } + + /// + /// Returns true if FormatTest instances are equal + /// + /// Instance of FormatTest to be compared + /// Boolean + public bool Equals(FormatTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Integer == other.Integer || + this.Integer != null && + this.Integer.Equals(other.Integer) + ) && + ( + this.Int32 == other.Int32 || + this.Int32 != null && + this.Int32.Equals(other.Int32) + ) && + ( + this.Int64 == other.Int64 || + this.Int64 != null && + this.Int64.Equals(other.Int64) + ) && + ( + this.Number == other.Number || + this.Number != null && + this.Number.Equals(other.Number) + ) && + ( + this._Float == other._Float || + this._Float != null && + this._Float.Equals(other._Float) + ) && + ( + this._Double == other._Double || + this._Double != null && + this._Double.Equals(other._Double) + ) && + ( + this._String == other._String || + this._String != null && + this._String.Equals(other._String) + ) && + ( + this._Byte == other._Byte || + this._Byte != null && + this._Byte.Equals(other._Byte) + ) && + ( + this.Binary == other.Binary || + this.Binary != null && + this.Binary.Equals(other.Binary) + ) && + ( + this.Date == other.Date || + this.Date != null && + this.Date.Equals(other.Date) + ) && + ( + this.DateTime == other.DateTime || + this.DateTime != null && + this.DateTime.Equals(other.DateTime) + ) && + ( + this.Uuid == other.Uuid || + this.Uuid != null && + this.Uuid.Equals(other.Uuid) + ) && + ( + this.Password == other.Password || + this.Password != null && + this.Password.Equals(other.Password) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Integer != null) + hash = hash * 59 + this.Integer.GetHashCode(); + if (this.Int32 != null) + hash = hash * 59 + this.Int32.GetHashCode(); + if (this.Int64 != null) + hash = hash * 59 + this.Int64.GetHashCode(); + if (this.Number != null) + hash = hash * 59 + this.Number.GetHashCode(); + if (this._Float != null) + hash = hash * 59 + this._Float.GetHashCode(); + if (this._Double != null) + hash = hash * 59 + this._Double.GetHashCode(); + if (this._String != null) + hash = hash * 59 + this._String.GetHashCode(); + if (this._Byte != null) + hash = hash * 59 + this._Byte.GetHashCode(); + if (this.Binary != null) + hash = hash * 59 + this.Binary.GetHashCode(); + if (this.Date != null) + hash = hash * 59 + this.Date.GetHashCode(); + if (this.DateTime != null) + hash = hash * 59 + this.DateTime.GetHashCode(); + if (this.Uuid != null) + hash = hash * 59 + this.Uuid.GetHashCode(); + if (this.Password != null) + hash = hash * 59 + this.Password.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + // Integer (int?) maximum + if(this.Integer > (int?)100.0) + { + yield return new ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.0.", new [] { "Integer" }); + } + + // Integer (int?) minimum + if(this.Integer < (int?)10.0) + { + yield return new ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.0.", new [] { "Integer" }); + } + + // Int32 (int?) maximum + if(this.Int32 > (int?)200.0) + { + yield return new ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.0.", new [] { "Int32" }); + } + + // Int32 (int?) minimum + if(this.Int32 < (int?)20.0) + { + yield return new ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.0.", new [] { "Int32" }); + } + + // Number (decimal?) maximum + if(this.Number > (decimal?)543.2) + { + yield return new 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 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 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 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 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 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 ValidationResult("Invalid value for _String, must match a pattern of /[a-z]/i.", new [] { "_String" }); + } + + // Password (string) maxLength + if(this.Password != null && this.Password.Length > 64) + { + yield return new 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 ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.cs new file mode 100644 index 00000000000..4fc798b7e70 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// HasOnlyReadOnly + /// + [DataContract] + [ImplementPropertyChanged] + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as HasOnlyReadOnly); + } + + /// + /// Returns true if HasOnlyReadOnly instances are equal + /// + /// Instance of HasOnlyReadOnly to be compared + /// Boolean + public bool Equals(HasOnlyReadOnly other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Bar == other.Bar || + this.Bar != null && + this.Bar.Equals(other.Bar) + ) && + ( + this.Foo == other.Foo || + this.Foo != null && + this.Foo.Equals(other.Foo) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Bar != null) + hash = hash * 59 + this.Bar.GetHashCode(); + if (this.Foo != null) + hash = hash * 59 + this.Foo.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs new file mode 100644 index 00000000000..c9f6b6be4f9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// List + /// + [DataContract] + [ImplementPropertyChanged] + public partial class List : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _123List. + public List(string _123List = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as List); + } + + /// + /// Returns true if List instances are equal + /// + /// Instance of List to be compared + /// Boolean + public bool Equals(List other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._123List == other._123List || + this._123List != null && + this._123List.Equals(other._123List) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._123List != null) + hash = hash * 59 + this._123List.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs new file mode 100644 index 00000000000..243c855b4fd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs @@ -0,0 +1,185 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// MapTest + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, Dictionary MapOfEnumString = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as MapTest); + } + + /// + /// Returns true if MapTest instances are equal + /// + /// Instance of MapTest to be compared + /// Boolean + public bool Equals(MapTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.MapMapOfString == other.MapMapOfString || + this.MapMapOfString != null && + this.MapMapOfString.SequenceEqual(other.MapMapOfString) + ) && + ( + this.MapOfEnumString == other.MapOfEnumString || + this.MapOfEnumString != null && + this.MapOfEnumString.SequenceEqual(other.MapOfEnumString) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.MapMapOfString != null) + hash = hash * 59 + this.MapMapOfString.GetHashCode(); + if (this.MapOfEnumString != null) + hash = hash * 59 + this.MapOfEnumString.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs new file mode 100644 index 00000000000..61adb990383 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -0,0 +1,179 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// MixedPropertiesAndAdditionalPropertiesClass + /// + [DataContract] + [ImplementPropertyChanged] + public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Uuid. + /// DateTime. + /// Map. + public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = null, DateTime? DateTime = null, Dictionary Map = null) + { + this.Uuid = Uuid; + this.DateTime = DateTime; + this.Map = Map; + } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name="uuid", EmitDefaultValue=false)] + public Guid? Uuid { get; set; } + /// + /// Gets or Sets DateTime + /// + [DataMember(Name="dateTime", EmitDefaultValue=false)] + public DateTime? DateTime { get; set; } + /// + /// Gets or Sets Map + /// + [DataMember(Name="map", EmitDefaultValue=false)] + public Dictionary Map { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as MixedPropertiesAndAdditionalPropertiesClass); + } + + /// + /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal + /// + /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(MixedPropertiesAndAdditionalPropertiesClass other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Uuid == other.Uuid || + this.Uuid != null && + this.Uuid.Equals(other.Uuid) + ) && + ( + this.DateTime == other.DateTime || + this.DateTime != null && + this.DateTime.Equals(other.DateTime) + ) && + ( + this.Map == other.Map || + this.Map != null && + this.Map.SequenceEqual(other.Map) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Uuid != null) + hash = hash * 59 + this.Uuid.GetHashCode(); + if (this.DateTime != null) + hash = hash * 59 + this.DateTime.GetHashCode(); + if (this.Map != null) + hash = hash * 59 + this.Map.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs new file mode 100644 index 00000000000..0e6db28041e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model name starting with number + /// + [DataContract] + [ImplementPropertyChanged] + public partial class Model200Response : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name. + /// _Class. + public Model200Response(int? Name = null, string _Class = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Model200Response); + } + + /// + /// Returns true if Model200Response instances are equal + /// + /// Instance of Model200Response to be compared + /// Boolean + public bool Equals(Model200Response other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Name == other.Name || + this.Name != null && + this.Name.Equals(other.Name) + ) && + ( + this._Class == other._Class || + this._Class != null && + this._Class.Equals(other._Class) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Name != null) + hash = hash * 59 + this.Name.GetHashCode(); + if (this._Class != null) + hash = hash * 59 + this._Class.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs new file mode 100644 index 00000000000..3d0f1af2ab7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// ModelClient + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ModelClient : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Client. + public ModelClient(string _Client = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ModelClient); + } + + /// + /// Returns true if ModelClient instances are equal + /// + /// Instance of ModelClient to be compared + /// Boolean + public bool Equals(ModelClient other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._Client == other._Client || + this._Client != null && + this._Client.Equals(other._Client) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._Client != null) + hash = hash * 59 + this._Client.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs new file mode 100644 index 00000000000..a092e681b5c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing reserved words + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ModelReturn : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Return. + public ModelReturn(int? _Return = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ModelReturn); + } + + /// + /// Returns true if ModelReturn instances are equal + /// + /// Instance of ModelReturn to be compared + /// Boolean + public bool Equals(ModelReturn other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._Return == other._Return || + this._Return != null && + this._Return.Equals(other._Return) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._Return != null) + hash = hash * 59 + this._Return.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs new file mode 100644 index 00000000000..31ebcde8efa --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs @@ -0,0 +1,203 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model name same as property name + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, string Property = null) + { + // 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Name); + } + + /// + /// Returns true if Name instances are equal + /// + /// Instance of Name to be compared + /// Boolean + public bool Equals(Name other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._Name == other._Name || + this._Name != null && + this._Name.Equals(other._Name) + ) && + ( + this.SnakeCase == other.SnakeCase || + this.SnakeCase != null && + this.SnakeCase.Equals(other.SnakeCase) + ) && + ( + this.Property == other.Property || + this.Property != null && + this.Property.Equals(other.Property) + ) && + ( + this._123Number == other._123Number || + this._123Number != null && + this._123Number.Equals(other._123Number) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._Name != null) + hash = hash * 59 + this._Name.GetHashCode(); + if (this.SnakeCase != null) + hash = hash * 59 + this.SnakeCase.GetHashCode(); + if (this.Property != null) + hash = hash * 59 + this.Property.GetHashCode(); + if (this._123Number != null) + hash = hash * 59 + this._123Number.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs new file mode 100644 index 00000000000..d3d5e5d3090 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// NumberOnly + /// + [DataContract] + [ImplementPropertyChanged] + public partial class NumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// JustNumber. + public NumberOnly(decimal? JustNumber = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as NumberOnly); + } + + /// + /// Returns true if NumberOnly instances are equal + /// + /// Instance of NumberOnly to be compared + /// Boolean + public bool Equals(NumberOnly other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.JustNumber == other.JustNumber || + this.JustNumber != null && + this.JustNumber.Equals(other.JustNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.JustNumber != null) + hash = hash * 59 + this.JustNumber.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs new file mode 100644 index 00000000000..1bf61b11df8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs @@ -0,0 +1,260 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Order + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, StatusEnum? Status = null, bool? Complete = null) + { + this.Id = Id; + this.PetId = PetId; + this.Quantity = Quantity; + this.ShipDate = ShipDate; + this.Status = Status; + // 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Order); + } + + /// + /// Returns true if Order instances are equal + /// + /// Instance of Order to be compared + /// Boolean + public bool Equals(Order other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Id == other.Id || + this.Id != null && + this.Id.Equals(other.Id) + ) && + ( + this.PetId == other.PetId || + this.PetId != null && + this.PetId.Equals(other.PetId) + ) && + ( + this.Quantity == other.Quantity || + this.Quantity != null && + this.Quantity.Equals(other.Quantity) + ) && + ( + this.ShipDate == other.ShipDate || + this.ShipDate != null && + this.ShipDate.Equals(other.ShipDate) + ) && + ( + this.Status == other.Status || + this.Status != null && + this.Status.Equals(other.Status) + ) && + ( + this.Complete == other.Complete || + this.Complete != null && + this.Complete.Equals(other.Complete) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Id != null) + hash = hash * 59 + this.Id.GetHashCode(); + if (this.PetId != null) + hash = hash * 59 + this.PetId.GetHashCode(); + if (this.Quantity != null) + hash = hash * 59 + this.Quantity.GetHashCode(); + if (this.ShipDate != null) + hash = hash * 59 + this.ShipDate.GetHashCode(); + if (this.Status != null) + hash = hash * 59 + this.Status.GetHashCode(); + if (this.Complete != null) + hash = hash * 59 + this.Complete.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs new file mode 100644 index 00000000000..c20ec7c1106 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs @@ -0,0 +1,273 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Pet + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, Category Category = null, string Name = null, List PhotoUrls = null, List Tags = null, StatusEnum? Status = null) + { + // 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Pet); + } + + /// + /// Returns true if Pet instances are equal + /// + /// Instance of Pet to be compared + /// Boolean + public bool Equals(Pet other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Id == other.Id || + this.Id != null && + this.Id.Equals(other.Id) + ) && + ( + this.Category == other.Category || + this.Category != null && + this.Category.Equals(other.Category) + ) && + ( + this.Name == other.Name || + this.Name != null && + this.Name.Equals(other.Name) + ) && + ( + this.PhotoUrls == other.PhotoUrls || + this.PhotoUrls != null && + this.PhotoUrls.SequenceEqual(other.PhotoUrls) + ) && + ( + this.Tags == other.Tags || + this.Tags != null && + this.Tags.SequenceEqual(other.Tags) + ) && + ( + this.Status == other.Status || + this.Status != null && + this.Status.Equals(other.Status) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Id != null) + hash = hash * 59 + this.Id.GetHashCode(); + if (this.Category != null) + hash = hash * 59 + this.Category.GetHashCode(); + if (this.Name != null) + hash = hash * 59 + this.Name.GetHashCode(); + if (this.PhotoUrls != null) + hash = hash * 59 + this.PhotoUrls.GetHashCode(); + if (this.Tags != null) + hash = hash * 59 + this.Tags.GetHashCode(); + if (this.Status != null) + hash = hash * 59 + this.Status.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs new file mode 100644 index 00000000000..4039c2bd3ee --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -0,0 +1,162 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// ReadOnlyFirst + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ReadOnlyFirst : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Baz. + public ReadOnlyFirst(string Baz = null) + { + this.Baz = Baz; + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name="bar", EmitDefaultValue=false)] + public string Bar { get; private set; } + /// + /// Gets or Sets Baz + /// + [DataMember(Name="baz", EmitDefaultValue=false)] + public string Baz { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ReadOnlyFirst {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Baz: ").Append(Baz).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ReadOnlyFirst); + } + + /// + /// Returns true if ReadOnlyFirst instances are equal + /// + /// Instance of ReadOnlyFirst to be compared + /// Boolean + public bool Equals(ReadOnlyFirst other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Bar == other.Bar || + this.Bar != null && + this.Bar.Equals(other.Bar) + ) && + ( + this.Baz == other.Baz || + this.Baz != null && + this.Baz.Equals(other.Baz) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Bar != null) + hash = hash * 59 + this.Bar.GetHashCode(); + if (this.Baz != null) + hash = hash * 59 + this.Baz.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs new file mode 100644 index 00000000000..7545aa5fa36 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs @@ -0,0 +1,149 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// SpecialModelName + /// + [DataContract] + [ImplementPropertyChanged] + public partial class SpecialModelName : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// SpecialPropertyName. + public SpecialModelName(long? SpecialPropertyName = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as SpecialModelName); + } + + /// + /// Returns true if SpecialModelName instances are equal + /// + /// Instance of SpecialModelName to be compared + /// Boolean + public bool Equals(SpecialModelName other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.SpecialPropertyName == other.SpecialPropertyName || + this.SpecialPropertyName != null && + this.SpecialPropertyName.Equals(other.SpecialPropertyName) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.SpecialPropertyName != null) + hash = hash * 59 + this.SpecialPropertyName.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs new file mode 100644 index 00000000000..54c13750f91 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Tag + /// + [DataContract] + [ImplementPropertyChanged] + public partial class Tag : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// Name. + public Tag(long? Id = null, string Name = null) + { + 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Tag); + } + + /// + /// Returns true if Tag instances are equal + /// + /// Instance of Tag to be compared + /// Boolean + public bool Equals(Tag other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Id == other.Id || + this.Id != null && + this.Id.Equals(other.Id) + ) && + ( + this.Name == other.Name || + this.Name != null && + this.Name.Equals(other.Name) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Id != null) + hash = hash * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hash = hash * 59 + this.Name.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs new file mode 100644 index 00000000000..988ec591edf --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs @@ -0,0 +1,255 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.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 PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// User + /// + [DataContract] + [ImplementPropertyChanged] + 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 = null, string Username = null, string FirstName = null, string LastName = null, string Email = null, string Password = null, string Phone = null, int? UserStatus = null) + { + this.Id = Id; + this.Username = Username; + this.FirstName = FirstName; + this.LastName = LastName; + this.Email = Email; + this.Password = Password; + this.Phone = Phone; + this.UserStatus = UserStatus; + } + + /// + /// 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 obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as User); + } + + /// + /// Returns true if User instances are equal + /// + /// Instance of User to be compared + /// Boolean + public bool Equals(User other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.Id == other.Id || + this.Id != null && + this.Id.Equals(other.Id) + ) && + ( + this.Username == other.Username || + this.Username != null && + this.Username.Equals(other.Username) + ) && + ( + this.FirstName == other.FirstName || + this.FirstName != null && + this.FirstName.Equals(other.FirstName) + ) && + ( + this.LastName == other.LastName || + this.LastName != null && + this.LastName.Equals(other.LastName) + ) && + ( + this.Email == other.Email || + this.Email != null && + this.Email.Equals(other.Email) + ) && + ( + this.Password == other.Password || + this.Password != null && + this.Password.Equals(other.Password) + ) && + ( + this.Phone == other.Phone || + this.Phone != null && + this.Phone.Equals(other.Phone) + ) && + ( + this.UserStatus == other.UserStatus || + this.UserStatus != null && + this.UserStatus.Equals(other.UserStatus) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.Id != null) + hash = hash * 59 + this.Id.GetHashCode(); + if (this.Username != null) + hash = hash * 59 + this.Username.GetHashCode(); + if (this.FirstName != null) + hash = hash * 59 + this.FirstName.GetHashCode(); + if (this.LastName != null) + hash = hash * 59 + this.LastName.GetHashCode(); + if (this.Email != null) + hash = hash * 59 + this.Email.GetHashCode(); + if (this.Password != null) + hash = hash * 59 + this.Password.GetHashCode(); + if (this.Phone != null) + hash = hash * 59 + this.Phone.GetHashCode(); + if (this.UserStatus != null) + hash = hash * 59 + this.UserStatus.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Properties/AssemblyInfo.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..f3b9f7d1d14 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/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/SwaggerClientWithPropertyChanged/src/IO.Swagger/packages.config b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/packages.config new file mode 100644 index 00000000000..9483191f247 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/packages.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/samples/client/petstore/dart/.analysis_options b/samples/client/petstore/dart/.analysis_options new file mode 100644 index 00000000000..518eb901a6f --- /dev/null +++ b/samples/client/petstore/dart/.analysis_options @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true \ No newline at end of file diff --git a/samples/client/petstore/dart/.swagger-codegen-ignore b/samples/client/petstore/dart/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/dart/.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/dart/lib/api/pet_api.dart b/samples/client/petstore/dart/lib/api/pet_api.dart deleted file mode 100644 index b6c807e72f0..00000000000 --- a/samples/client/petstore/dart/lib/api/pet_api.dart +++ /dev/null @@ -1,422 +0,0 @@ -part of api; - - -class PetApi { - String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; - - PetApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } - - /// Add a new pet to the store - /// - /// - Future addPet(Pet body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = ["application/json","application/xml"]; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Deletes a pet - /// - /// - Future deletePet(int petId, String apiKey) { - Object postBody = null; - // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - headerParams["api_key"] = apiKey; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Finds Pets by status - /// - /// Multiple status values can be provided with comma separated strings - Future> findPetsByStatus(List status) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet/findByStatus".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - if("null" != status) - queryParams["status"] = status is List ? status.join(',') : status; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); - } - /// Finds Pets by tags - /// - /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - Future> findPetsByTags(List tags) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet/findByTags".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - if("null" != tags) - queryParams["tags"] = tags is List ? tags.join(',') : tags; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); - } - /// Find pet by ID - /// - /// Returns a single pet - Future getPetById(int petId) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["api_key"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); - } - /// Update an existing pet - /// - /// - Future updatePet(Pet body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = ["application/json","application/xml"]; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Updates a pet in the store with form data - /// - /// - Future updatePetWithForm(int petId, String name, String status) { - Object postBody = null; - // verify required params are set - if( // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = ["application/x-www-form-urlencoded"]; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if (name != null) { - hasFields = true; - mp.fields['name'] = apiClient.parameterToString(name); - } - - if (status != null) { - hasFields = true; - mp.fields['status'] = apiClient.parameterToString(status); - } - - if(hasFields) - postBody = mp; - } - else { - if (name != null) - formParams['name'] = apiClient.parameterToString(name); -if (status != null) - formParams['status'] = apiClient.parameterToString(status); - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// uploads an image - /// - /// - Future uploadFile(int petId, String additionalMetadata, MultipartFile file) { - Object postBody = null; - // verify required params are set - if( // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/pet/{petId}/uploadImage".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = ["multipart/form-data"]; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["petstore_auth"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if (additionalMetadata != null) { - hasFields = true; - mp.fields['additionalMetadata'] = apiClient.parameterToString(additionalMetadata); - } - - if (file != null) { - hasFields = true; - mp.fields['file'] = file.field; - mp.files.add(file); - } - - if(hasFields) - postBody = mp; - } - else { - if (additionalMetadata != null) - formParams['additionalMetadata'] = apiClient.parameterToString(additionalMetadata); - - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, ApiResponse); - } - else { - return null; - } - }); - } -} diff --git a/samples/client/petstore/dart/lib/api/store_api.dart b/samples/client/petstore/dart/lib/api/store_api.dart deleted file mode 100644 index 25e3ccfcf6e..00000000000 --- a/samples/client/petstore/dart/lib/api/store_api.dart +++ /dev/null @@ -1,191 +0,0 @@ -part of api; - - -class StoreApi { - String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; - - StoreApi([ApiClient apiClient]) { - if (apiClient != null) { - 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 - Future deleteOrder(String orderId) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Returns pet inventories by status - /// - /// Returns a map of status codes to quantities - Future> getInventory() { - Object postBody = null; - - - // create path and map variables - String path = "/store/inventory".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = ["api_key"]; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Map); - } - else { - return null; - } - }); - } - /// Find purchase order by ID - /// - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - Future getOrderById(int orderId) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Order); - } - else { - return null; - } - }); - } - /// Place an order for a pet - /// - /// - Future placeOrder(Order body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/store/order".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Order); - } - else { - return null; - } - }); - } -} diff --git a/samples/client/petstore/dart/lib/api/user_api.dart b/samples/client/petstore/dart/lib/api/user_api.dart deleted file mode 100644 index d774ea1f931..00000000000 --- a/samples/client/petstore/dart/lib/api/user_api.dart +++ /dev/null @@ -1,381 +0,0 @@ -part of api; - - -class UserApi { - String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; - - UserApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } - - /// Create user - /// - /// This can only be done by the logged in user. - Future createUser(User body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Creates list of users with given input array - /// - /// - Future createUsersWithArrayInput(List body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/createWithArray".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Creates list of users with given input array - /// - /// - Future createUsersWithListInput(List body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/createWithList".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Delete user - /// - /// This can only be done by the logged in user. - Future deleteUser(String username) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Get user by user name - /// - /// - Future getUserByName(String username) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, User); - } - else { - return null; - } - }); - } - /// Logs user into the system - /// - /// - Future loginUser(String username, String password) { - Object postBody = null; - // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/login".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - if("null" != username) - queryParams["username"] = username is List ? username.join(',') : username; -if("null" != password) - queryParams["password"] = password is List ? password.join(',') : password; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, String); - } - else { - return null; - } - }); - } - /// Logs out current logged in user session - /// - /// - Future logoutUser() { - Object postBody = null; - - - // create path and map variables - String path = "/user/logout".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Updated user - /// - /// This can only be done by the logged in user. - Future updateUser(String username, User body) { - Object postBody = body; - // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } -} diff --git a/samples/client/petstore/dart/lib/api_client.dart b/samples/client/petstore/dart/lib/api_client.dart deleted file mode 100644 index c4e9a5b1d46..00000000000 --- a/samples/client/petstore/dart/lib/api_client.dart +++ /dev/null @@ -1,165 +0,0 @@ -part of api; - -class ApiClient { - static ApiClient defaultApiClient = new ApiClient(); - - Map _defaultHeaderMap = {}; - Map _authentications = {}; - static final dson = new Dartson.JSON(); - final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - - ApiClient() { - // Setup authentications (key: authentication name, value: authentication). - _authentications['petstore_auth'] = new OAuth(); - _authentications['api_key'] = new ApiKeyAuth("header", "api_key"); - } - - void addDefaultHeader(String key, String value) { - _defaultHeaderMap[key] = value; - } - - /// Format the given Date object into string. - String formatDate(DateTime date) { - return _dateFormatter.format(date); - } - - /// Format the given parameter object into string. - String parameterToString(Object param) { - if (param == null) { - return ''; - } else if (param is DateTime) { - return formatDate(param); - } else if (param is List) { - return (param).join(','); - } else { - return param.toString(); - } - } - - static dynamic deserialize(String json, dynamic clazz) { - var result = json; - - try { - var decodedJson = JSON.decode(json); - - if(decodedJson is List) { - result = []; - for(var obj in decodedJson) { - result.add(_createEntity(obj, clazz)); - } - } else { - result = _createEntity(json, clazz); - } - } on FormatException { - // Just return the passed in value - } - - return result; - } - - static dynamic _createEntity(dynamic json, dynamic clazz) { - bool isMap = json is Map; - - switch(clazz) { - case ApiResponse: - return isMap ? dson.map(json, new ApiResponse()) : dson.decode(json, new ApiResponse()); - case Category: - return isMap ? dson.map(json, new Category()) : dson.decode(json, new Category()); - case Order: - return isMap ? dson.map(json, new Order()) : dson.decode(json, new Order()); - case Pet: - return isMap ? dson.map(json, new Pet()) : dson.decode(json, new Pet()); - case Tag: - return isMap ? dson.map(json, new Tag()) : dson.decode(json, new Tag()); - case User: - return isMap ? dson.map(json, new User()) : dson.decode(json, new User()); - default: - throw new ApiException(500, 'Could not find a suitable class for deserialization'); - } - } - - static String serialize(Object obj) { - String serialized = ''; - if (obj == null) { - serialized = ''; - } else if (obj is String) { - serialized = obj; - } else { - serialized = dson.encode(obj); - } - return serialized; - } - - Future invokeAPI( String host, - String path, - String method, - Map queryParams, - Object body, - Map headerParams, - Map formParams, - String contentType, - List authNames) { - - updateParamsForAuth(authNames, queryParams, headerParams); - - var client = new BrowserClient(); - - StringBuffer sb = new StringBuffer(); - - for(String key in queryParams.keys) { - String value = queryParams[key]; - if (value != null){ - if(sb.toString().length == 0) { - sb.write("?"); - } else { - sb.write("&"); - } - sb.write(key); - sb.write("="); - sb.write(value); - } - } - String querystring = sb.toString(); - - String url = host + path + querystring; - - headerParams.addAll(_defaultHeaderMap); - headerParams['Content-Type'] = contentType; - - var completer = new Completer(); - - if(body is MultipartRequest) { - var request = new MultipartRequest(method, Uri.parse(url)); - request.fields.addAll(body.fields); - request.files.addAll(body.files); - request.headers.addAll(body.headers); - request.headers.addAll(headerParams); - client.send(request).then((response) => completer.complete(Response.fromStream(response))); - } else { - var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); - switch(method) { - case "GET": - return client.get(url, headers: headerParams); - case "POST": - return client.post(url, headers: headerParams, body: msgBody); - case "PUT": - return client.put(url, headers: headerParams, body: msgBody); - case "DELETE": - return client.delete(url, headers: headerParams); - } - } - - return completer.future; - } - - /// Update query and header parameters based on authentication settings. - /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { - authNames.forEach((authName) { - Authentication auth = _authentications[authName]; - if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - }); - } - -} diff --git a/samples/client/petstore/dart/lib/api_exception.dart b/samples/client/petstore/dart/lib/api_exception.dart deleted file mode 100644 index c168fb512da..00000000000 --- a/samples/client/petstore/dart/lib/api_exception.dart +++ /dev/null @@ -1,9 +0,0 @@ -part of api; - -class ApiException implements Exception { - int code = 0; - String message = null; - - ApiException(this.code, this.message); - -} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/lib/auth/api_key_auth.dart deleted file mode 100644 index 6e728ae916b..00000000000 --- a/samples/client/petstore/dart/lib/auth/api_key_auth.dart +++ /dev/null @@ -1,28 +0,0 @@ -part of api; - -class ApiKeyAuth implements Authentication { - - final String location; - final String paramName; - String apiKey; - String apiKeyPrefix; - - ApiKeyAuth(this.location, this.paramName); - - @override - void applyToParams(Map queryParams, Map headerParams) { - String value; - if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; - } else { - value = apiKey; - } - - if (location == 'query' && value != null) { - queryParams[paramName] = value; - } else if (location == 'header' && value != null) { - headerParams[paramName] = value; - } - } - -} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/authentication.dart b/samples/client/petstore/dart/lib/auth/authentication.dart deleted file mode 100644 index 4833af90ec0..00000000000 --- a/samples/client/petstore/dart/lib/auth/authentication.dart +++ /dev/null @@ -1,7 +0,0 @@ -part of api; - -abstract class Authentication { - - /// Apply authentication settings to header and query params. - void applyToParams(Map queryParams, Map headerParams); -} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart deleted file mode 100644 index e681c25653d..00000000000 --- a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart +++ /dev/null @@ -1,14 +0,0 @@ -part of api; - -class HttpBasicAuth implements Authentication { - - String username; - String password; - - @override - void applyToParams(Map queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); - } - -} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/oauth.dart b/samples/client/petstore/dart/lib/auth/oauth.dart deleted file mode 100644 index 5e3e2c8b260..00000000000 --- a/samples/client/petstore/dart/lib/auth/oauth.dart +++ /dev/null @@ -1,9 +0,0 @@ -part of api; - -class OAuth implements Authentication { - - @override - void applyToParams(Map queryParams, Map headerParams) { - // TODO: support oauth - } -} \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/.analysis_options b/samples/client/petstore/dart/petstore/.analysis_options new file mode 100644 index 00000000000..a10d4c5a05c --- /dev/null +++ b/samples/client/petstore/dart/petstore/.analysis_options @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true diff --git a/samples/client/petstore/dart/petstore/LICENSE b/samples/client/petstore/dart/petstore/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/dart/petstore/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/dart/petstore/README.md b/samples/client/petstore/dart/petstore/README.md new file mode 100644 index 00000000000..17343a5c026 --- /dev/null +++ b/samples/client/petstore/dart/petstore/README.md @@ -0,0 +1,58 @@ +# To run these tests: + +Simply start the dart server: `pub serve` + +then open http://127.0.0.1:8080/tests.html + + +This already starts the tests. There is _NO_ feedback! + +Open the javascript / dart console of your browser to verify all tests +passed successfully. + +You should have the following output: +``` +Observatory listening at http://127.0.0.1:39067/ +unittest-suite-wait-for-done +GET http://petstore.swagger.io/v2/pet/957639 404 (Not Found) +GET http://petstore.swagger.io/v2/pet/525946 404 (Not Found) +GET http://petstore.swagger.io/v2/store/order/29756 404 (Not Found) +GET http://petstore.swagger.io/v2/user/Riddlem325 404 (Not Found) +PASS: Pet API adds a new pet and gets it by id +PASS: Pet API doesn't get non-existing pet by id +PASS: Pet API deletes existing pet by id +PASS: Pet API updates pet with form +PASS: Pet API updates existing pet +PASS: Pet API finds pets by status +PASS: Pet API finds pets by tag +PASS: Pet API uploads a pet image +PASS: Store API places an order and gets it by id +PASS: Store API deletes an order +PASS: Store API gets the store inventory +PASS: User API creates a user +PASS: User API creates users with list input +PASS: User API updates a user +PASS: User API deletes a user +PASS: User API logs a user in + +All 16 tests passed. +unittest-suite-success +``` + + +You may also run the tests in the dart vm. + +Either generate the test-package for a vm: +- change bin/dart-petstore.sh and uncomment the vm options line +- run bin/dart-petstore.sh + +or + +- in `lib/api_client.dart` change `new BrowserClient()` to `new Client()` +- in `lib/api.dart` remove the line `import 'package:http/browser_client.dart';` + + + +Then run `test/tests.dart`. + +Have fun. \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/pubspec.yaml b/samples/client/petstore/dart/petstore/pubspec.yaml new file mode 100644 index 00000000000..26f7d22205d --- /dev/null +++ b/samples/client/petstore/dart/petstore/pubspec.yaml @@ -0,0 +1,9 @@ +name: petstore_client +version: 1.0.0 +description: Petstore client using swagger API library +dependencies: + swagger: + path: ../swagger + +dev_dependencies: + guinness: '^0.1.17' \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/test/browser/packages b/samples/client/petstore/dart/petstore/test/browser/packages new file mode 100644 index 00000000000..4b727bf6889 --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/browser/packages @@ -0,0 +1 @@ +../../packages \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/test/packages b/samples/client/petstore/dart/petstore/test/packages new file mode 100644 index 00000000000..a16c4050155 --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/packages @@ -0,0 +1 @@ +../packages \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/test/pet_test.dart b/samples/client/petstore/dart/petstore/test/pet_test.dart new file mode 100644 index 00000000000..213396f29cb --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/pet_test.dart @@ -0,0 +1,81 @@ +part of tests; + +testPetApi() { + var petApi = new PetApi(); + + describe('Pet API ', () { + it('adds a new pet and gets it by id', () async { + var id = newId(); + + await petApi.addPet(new Pet()..id = id); + var pet = await petApi.getPetById(id); + expect(pet.id).toEqual(id); + }); + + it('doesn\'t get non-existing pet by id', () { + expect(petApi.getPetById(newId())) + .toThrowWith(anInstanceOf: ApiException); + }); + + it('deletes existing pet by id', () async { + var id = newId(); + await petApi.addPet(new Pet()..id = id); + await petApi.deletePet(id, apiKey: 'special-key'); + expect(petApi.getPetById(id)).toThrowWith(anInstanceOf: ApiException); + }); + + it('updates pet with form', () async { + var id = newId(); + await petApi.addPet(new Pet() + ..id = id + ..name = 'Snowy'); + await petApi.updatePetWithForm(id, name: 'Doge', status: ''); + var pet = await petApi.getPetById(id); + expect(pet.name).toEqual('Doge'); + }); + + it('updates existing pet', () async { + var id = newId(); + var name = 'Snowy'; + + await petApi.addPet(new Pet()..id = id); + await petApi.updatePet(new Pet() + ..id = id + ..name = name); + var pet = await petApi.getPetById(id); + expect(pet.name).toEqual(name); + }); + + it('finds pets by status', () async { + var id1 = newId(); + var id2 = newId(); + var id3 = newId(); + var status = 'available'; + + return Future.wait([ + petApi.addPet(new Pet() + ..id = id1 + ..status = status), + petApi.addPet(new Pet() + ..id = id2 + ..status = status), + petApi.addPet(new Pet() + ..id = id3 + ..status = 'sold') + ]).then((_) async { + var pets = await petApi.findPetsByStatus([status]); + var petIds = pets.map((pet) => pet.id).toList(); + expect(petIds).toContain(id1); + expect(petIds).toContain(id2); + expect(petIds).not.toContain(id3); + }); + }); + + it('uploads a pet image', () async { + var id = newId(); + await petApi.addPet(new Pet()..id = id); + var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); + await petApi.uploadFile(id, additionalMetadata: '', file: file); + }); + }); +} diff --git a/samples/client/petstore/dart/petstore/test/store_test.dart b/samples/client/petstore/dart/petstore/test/store_test.dart new file mode 100644 index 00000000000..39d9cecfac7 --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/store_test.dart @@ -0,0 +1,28 @@ +part of tests; + +testStoreApi() { + var storeApi = new StoreApi(); + + describe('Store API ', () { + it('places an order and gets it by id', () async { + var id = newId(); + + await storeApi.placeOrder(new Order()..id = id); + var order = await storeApi.getOrderById(id); + expect(order.id).toEqual(id); + }); + + it('deletes an order', () async { + var id = newId(); + + await storeApi.placeOrder(new Order()..id = id); + await storeApi.deleteOrder(id.toString()); + expect(storeApi.getOrderById(id)).toThrowWith(anInstanceOf: ApiException); + }); + + it('gets the store inventory', () async { + Map inventory = await storeApi.getInventory(); + expect(inventory.length).not.toBe(0); + }); + }); +} diff --git a/samples/client/petstore/dart/petstore/test/tests.dart b/samples/client/petstore/dart/petstore/test/tests.dart new file mode 100644 index 00000000000..9511ea17875 --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/tests.dart @@ -0,0 +1,23 @@ +library tests; + +import 'dart:async'; +import 'dart:math'; +import 'package:http/http.dart'; +import 'package:guinness/guinness.dart'; +import 'package:swagger/api.dart'; + +part 'pet_test.dart'; +part 'store_test.dart'; +part 'user_test.dart'; + +final random = new Random(); + +int newId() { + return random.nextInt(999999); +} + +main() { + testPetApi(); + testStoreApi(); + testUserApi(); +} diff --git a/samples/client/petstore/dart/test/tests.html b/samples/client/petstore/dart/petstore/test/tests.html similarity index 100% rename from samples/client/petstore/dart/test/tests.html rename to samples/client/petstore/dart/petstore/test/tests.html diff --git a/samples/client/petstore/dart/petstore/test/user_test.dart b/samples/client/petstore/dart/petstore/test/user_test.dart new file mode 100644 index 00000000000..7188a1d25ea --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/user_test.dart @@ -0,0 +1,77 @@ +part of tests; + +testUserApi() { + var userApi = new UserApi(); + + describe('User API ', () { + it('creates a user', () async { + var id = newId(); + var username = 'Mally45'; + await userApi.createUser(new User() + ..id = id + ..username = username); + var user = await userApi.getUserByName(username); + expect(user.id).toEqual(id); + }); + + it('creates users with list input', () async { + var firstId = newId(); + var joe = 'Joe'; + + var sally = 'Sally'; + var secondId = newId(); + + var users = [ + new User() + ..id = firstId + ..username = joe, + new User() + ..id = secondId + ..username = sally + ]; + + await userApi.createUsersWithListInput(users); + var firstUser = await userApi.getUserByName(joe); + var secondUser = await userApi.getUserByName(sally); + expect(firstUser.id).toEqual(firstId); + expect(secondUser.id).toEqual(secondId); + }); + + it('updates a user', () async { + var username = 'Arkjam89'; + var email = 'test@example.com'; + var user = new User() + ..id = newId() + ..username = username; + + await userApi.createUser(user); + user.email = email; + await userApi.updateUser(username, user); + var foundUser = await userApi.getUserByName(username); + expect(foundUser.email).toEqual(email); + }); + + it('deletes a user', () async { + var username = 'Riddlem325'; + await userApi.createUser(new User() + ..id = newId() + ..username = username); + await userApi.deleteUser(username); + expect(userApi.getUserByName(username)) + .toThrowWith(anInstanceOf: ApiException); + }); + + it('logs a user in', () async { + var username = 'sgarad625'; + var password = 'lokimoki1'; + var user = new User() + ..id = newId() + ..username = username + ..password = password; + + await userApi.createUser(user); + var result = await userApi.loginUser(username, password); + expect(result).toContain('logged in user session:'); + }); + }); +} diff --git a/samples/client/petstore/dart/pubspec.lock b/samples/client/petstore/dart/pubspec.lock deleted file mode 100644 index 1e4ba01779c..00000000000 --- a/samples/client/petstore/dart/pubspec.lock +++ /dev/null @@ -1,87 +0,0 @@ -# Generated by pub -# See http://pub.dartlang.org/doc/glossary.html#lockfile -packages: - analyzer: - description: analyzer - source: hosted - version: "0.25.0+1" - args: - description: args - source: hosted - version: "0.13.2" - barback: - description: barback - source: hosted - version: "0.15.2+4" - browser: - description: browser - source: hosted - version: "0.10.0+2" - collection: - description: collection - source: hosted - version: "1.1.1" - crypto: - description: crypto - source: hosted - version: "0.9.0" - dartson: - description: dartson - source: hosted - version: "0.2.4" - guinness: - description: guinness - source: hosted - version: "0.1.17" - http: - description: http - source: hosted - version: "0.11.2" - http_parser: - description: http_parser - source: hosted - version: "0.0.2+7" - intl: - description: intl - source: hosted - version: "0.12.4+2" - logging: - description: logging - source: hosted - version: "0.9.3" - path: - description: path - source: hosted - version: "1.3.6" - petitparser: - description: petitparser - source: hosted - version: "1.4.3" - pool: - description: pool - source: hosted - version: "1.1.0" - source_maps: - description: source_maps - source: hosted - version: "0.10.1" - source_span: - description: source_span - source: hosted - version: "1.1.2" - stack_trace: - description: stack_trace - source: hosted - version: "1.3.4" - string_scanner: - description: string_scanner - source: hosted - version: "0.1.3+1" - unittest: - description: unittest - source: hosted - version: "0.11.6+1" - watcher: - description: watcher - source: hosted - version: "0.9.6" diff --git a/samples/client/petstore/dart/pubspec.yaml b/samples/client/petstore/dart/pubspec.yaml deleted file mode 100644 index cbc62b63ca1..00000000000 --- a/samples/client/petstore/dart/pubspec.yaml +++ /dev/null @@ -1,15 +0,0 @@ -name: swagger -version: 1.0.0 -description: Swagger API client -dependencies: - http: '>=0.11.1 <0.12.0' - dartson: "^0.2.4" - crypto: "^0.9.0" - intl: "^0.12.4+2" - -dev_dependencies: - guinness: '^0.1.17' - browser: any - -transformers: - - dartson diff --git a/samples/client/petstore/dart/swagger/.analysis_options b/samples/client/petstore/dart/swagger/.analysis_options new file mode 100644 index 00000000000..518eb901a6f --- /dev/null +++ b/samples/client/petstore/dart/swagger/.analysis_options @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true \ No newline at end of file diff --git a/samples/client/petstore/dart/swagger/.gitignore b/samples/client/petstore/dart/swagger/.gitignore new file mode 100644 index 00000000000..7c280441649 --- /dev/null +++ b/samples/client/petstore/dart/swagger/.gitignore @@ -0,0 +1,27 @@ +# See https://www.dartlang.org/tools/private-files.html + +# Files and directories created by pub +.buildlog +.packages +.project +.pub/ +build/ +**/packages/ + +# Files created by dart2js +# (Most Dart developers will use pub build to compile Dart, use/modify these +# rules if you intend to use dart2js directly +# Convention is to use extension '.dart.js' for Dart compiled to Javascript to +# differentiate from explicit Javascript files) +*.dart.js +*.part.js +*.js.deps +*.js.map +*.info.json + +# Directory created by dartdoc +doc/api/ + +# Don't commit pubspec lock file +# (Library packages only! Remove pattern if developing an application package) +pubspec.lock diff --git a/samples/client/petstore/dart/swagger/LICENSE b/samples/client/petstore/dart/swagger/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/dart/swagger/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/dart/swagger/git_push.sh b/samples/client/petstore/dart/swagger/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/dart/swagger/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/dart/lib/api.dart b/samples/client/petstore/dart/swagger/lib/api.dart similarity index 80% rename from samples/client/petstore/dart/lib/api.dart rename to samples/client/petstore/dart/swagger/lib/api.dart index c296270af64..db95000d614 100644 --- a/samples/client/petstore/dart/lib/api.dart +++ b/samples/client/petstore/dart/swagger/lib/api.dart @@ -1,15 +1,15 @@ -library api; +library swagger.api; import 'dart:async'; import 'dart:convert'; -import 'dart:html'; import 'package:http/browser_client.dart'; import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; -import 'package:crypto/crypto.dart'; +import 'package:dartson/transformers/date_time.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; +part 'api_helper.dart'; part 'api_exception.dart'; part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; @@ -27,3 +27,6 @@ part 'model/pet.dart'; part 'model/tag.dart'; part 'model/user.dart'; + +ApiClient defaultApiClient = new ApiClient(); + diff --git a/samples/client/petstore/dart/swagger/lib/api/pet_api.dart b/samples/client/petstore/dart/swagger/lib/api/pet_api.dart new file mode 100644 index 00000000000..45c203c51ef --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api/pet_api.dart @@ -0,0 +1,481 @@ +part of swagger.api; + + + +class PetApi { + final ApiClient apiClient; + + PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + + /// Add a new pet to the store + /// + /// + Future addPet(Pet body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/pet".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = ["application/json","application/xml"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Deletes a pet + /// + /// + Future deletePet(int petId, { String apiKey, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); + } + + // create path and map variables + String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + headerParams["api_key"] = apiKey; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma separated strings + Future> findPetsByStatus(List status, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(status == null) { + throw new ApiException(400, "Missing required param: status"); + } + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + queryParams.addAll(_convertParametersForCollectionFormat("csv", "status", status)); + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'List') as List ; + } else { + return null; + } + } + /// Finds Pets by tags + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + Future> findPetsByTags(List tags, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(tags == null) { + throw new ApiException(400, "Missing required param: tags"); + } + + // create path and map variables + String path = "/pet/findByTags".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + queryParams.addAll(_convertParametersForCollectionFormat("csv", "tags", tags)); + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'List') as List ; + } else { + return null; + } + } + /// Find pet by ID + /// + /// Returns a single pet + Future getPetById(int petId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); + } + + // create path and map variables + String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["api_key"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Pet') as Pet ; + } else { + return null; + } + } + /// Update an existing pet + /// + /// + Future updatePet(Pet body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/pet".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = ["application/json","application/xml"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Updates a pet in the store with form data + /// + /// + Future updatePetWithForm(int petId, { String name, String status, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); + } + + // create path and map variables + String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = ["application/x-www-form-urlencoded"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if (name != null) { + hasFields = true; + mp.fields['name'] = apiClient.parameterToString(name); + } + + if (status != null) { + hasFields = true; + mp.fields['status'] = apiClient.parameterToString(status); + } + + if(hasFields) + postBody = mp; + } + else { + if (name != null) + formParams['name'] = apiClient.parameterToString(name); +if (status != null) + formParams['status'] = apiClient.parameterToString(status); + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// uploads an image + /// + /// + Future uploadFile(int petId, { String additionalMetadata, MultipartFile file, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); + } + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = ["multipart/form-data"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if (additionalMetadata != null) { + hasFields = true; + mp.fields['additionalMetadata'] = apiClient.parameterToString(additionalMetadata); + } + + if (file != null) { + hasFields = true; + mp.fields['file'] = file.field; + mp.files.add(file); + } + + if(hasFields) + postBody = mp; + } + else { + if (additionalMetadata != null) + formParams['additionalMetadata'] = apiClient.parameterToString(additionalMetadata); + + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'ApiResponse') as ApiResponse ; + } else { + return null; + } + } +} diff --git a/samples/client/petstore/dart/swagger/lib/api/store_api.dart b/samples/client/petstore/dart/swagger/lib/api/store_api.dart new file mode 100644 index 00000000000..a2bf1bb68b9 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api/store_api.dart @@ -0,0 +1,227 @@ +part of swagger.api; + + + +class StoreApi { + final ApiClient apiClient; + + StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + + /// Delete purchase order by ID + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + Future deleteOrder(String orderId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(orderId == null) { + throw new ApiException(400, "Missing required param: orderId"); + } + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + Future> getInventory( { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + + // create path and map variables + String path = "/store/inventory".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["api_key"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Map') as Map ; + } else { + return null; + } + } + /// Find purchase order by ID + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + Future getOrderById(int orderId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(orderId == null) { + throw new ApiException(400, "Missing required param: orderId"); + } + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Order') as Order ; + } else { + return null; + } + } + /// Place an order for a pet + /// + /// + Future placeOrder(Order body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/store/order".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Order') as Order ; + } else { + return null; + } + } +} diff --git a/samples/client/petstore/dart/swagger/lib/api/user_api.dart b/samples/client/petstore/dart/swagger/lib/api/user_api.dart new file mode 100644 index 00000000000..10fecbf80f0 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api/user_api.dart @@ -0,0 +1,455 @@ +part of swagger.api; + + + +class UserApi { + final ApiClient apiClient; + + UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + + /// Create user + /// + /// This can only be done by the logged in user. + Future createUser(User body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/user".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Creates list of users with given input array + /// + /// + Future createUsersWithArrayInput(List body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/user/createWithArray".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Creates list of users with given input array + /// + /// + Future createUsersWithListInput(List body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/user/createWithList".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Delete user + /// + /// This can only be done by the logged in user. + Future deleteUser(String username, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Get user by user name + /// + /// + Future getUserByName(String username, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'User') as User ; + } else { + return null; + } + } + /// Logs user into the system + /// + /// + Future loginUser(String username, String password, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + if(password == null) { + throw new ApiException(400, "Missing required param: password"); + } + + // create path and map variables + String path = "/user/login".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + queryParams.addAll(_convertParametersForCollectionFormat("", "username", username)); + queryParams.addAll(_convertParametersForCollectionFormat("", "password", password)); + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'String') as String ; + } else { + return null; + } + } + /// Logs out current logged in user session + /// + /// + Future logoutUser( { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + + // create path and map variables + String path = "/user/logout".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Updated user + /// + /// This can only be done by the logged in user. + Future updateUser(String username, User body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } +} diff --git a/samples/client/petstore/dart/swagger/lib/api_client.dart b/samples/client/petstore/dart/swagger/lib/api_client.dart new file mode 100644 index 00000000000..73856b69d74 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api_client.dart @@ -0,0 +1,176 @@ +part of swagger.api; + +class QueryParam { + String name; + String value; + + QueryParam(this.name, this.value); +} + +class ApiClient { + + String basePath; + var client = new BrowserClient(); + + Map _defaultHeaderMap = {}; + Map _authentications = {}; + + final dson = new Dartson.JSON() + ..addTransformer(new DateTimeParser(), DateTime); + final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + final _RegList = new RegExp(r'^List<(.*)>$'); + final _RegMap = new RegExp(r'^Map$'); + + ApiClient({this.basePath: "http://petstore.swagger.io/v2"}) { + // Setup authentications (key: authentication name, value: authentication). + _authentications['api_key'] = new ApiKeyAuth("header", "api_key"); + _authentications['petstore_auth'] = new OAuth(); + } + + void addDefaultHeader(String key, String value) { + _defaultHeaderMap[key] = value; + } + + /// Format the given Date object into string. + String formatDate(DateTime date) { + return _dateFormatter.format(date); + } + + /// Format the given parameter object into string. + String parameterToString(Object param) { + if (param == null) { + return ''; + } else if (param is DateTime) { + return formatDate(param); + } else if (param is List) { + return (param).join(','); + } else { + return param.toString(); + } + } + + dynamic _deserialize(dynamic value, String targetType) { + try { + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + return value is bool ? value : '$value'.toLowerCase() == 'true'; + case 'double': + return value is double ? value : double.parse('$value'); + case 'ApiResponse': + return dson.map(value, new ApiResponse()); + case 'Category': + return dson.map(value, new Category()); + case 'Order': + return dson.map(value, new Order()); + case 'Pet': + return dson.map(value, new Pet()); + case 'Tag': + return dson.map(value, new Tag()); + case 'User': + return dson.map(value, new User()); + default: + { + Match match; + if (value is List && + (match = _RegList.firstMatch(targetType)) != null) { + var newTargetType = match[1]; + return value.map((v) => _deserialize(v, newTargetType)).toList(); + } else if (value is Map && + (match = _RegMap.firstMatch(targetType)) != null) { + var newTargetType = match[1]; + return new Map.fromIterables(value.keys, + value.values.map((v) => _deserialize(v, newTargetType))); + } + } + } + } catch (e, stack) { + throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack); + } + throw new ApiException(500, 'Could not find a suitable class for deserialization'); + } + + dynamic deserialize(String json, String targetType) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); + + if (targetType == 'String') return json; + + var decodedJson = JSON.decode(json); + return _deserialize(decodedJson, targetType); + } + + String serialize(Object obj) { + String serialized = ''; + if (obj == null) { + serialized = ''; + } else if (obj is String) { + serialized = obj; + } else { + serialized = dson.encode(obj); + } + return serialized; + } + + // We don't use a Map for queryParams. + // If collectionFormat is 'multi' a key might appear multiple times. + Future invokeAPI(String path, + String method, + Iterable queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) async { + + _updateParamsForAuth(authNames, queryParams, headerParams); + + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + String queryString = ps.isNotEmpty ? + '?' + ps.join('&') : + ''; + + String url = basePath + path + queryString; + + headerParams.addAll(_defaultHeaderMap); + headerParams['Content-Type'] = contentType; + + if(body is MultipartRequest) { + var request = new MultipartRequest(method, Uri.parse(url)); + request.fields.addAll(body.fields); + request.files.addAll(body.files); + request.headers.addAll(body.headers); + request.headers.addAll(headerParams); + var response = await client.send(request); + return Response.fromStream(response); + } else { + var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); + switch(method) { + case "POST": + return client.post(url, headers: headerParams, body: msgBody); + case "PUT": + return client.put(url, headers: headerParams, body: msgBody); + case "DELETE": + return client.delete(url, headers: headerParams); + case "PATCH": + return client.patch(url, headers: headerParams, body: msgBody); + default: + return client.get(url, headers: headerParams); + } + } + } + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { + authNames.forEach((authName) { + Authentication auth = _authentications[authName]; + if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + }); + } +} diff --git a/samples/client/petstore/dart/swagger/lib/api_exception.dart b/samples/client/petstore/dart/swagger/lib/api_exception.dart new file mode 100644 index 00000000000..b861591bec0 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api_exception.dart @@ -0,0 +1,23 @@ +part of swagger.api; + +class ApiException implements Exception { + int code = 0; + String message = null; + Exception innerException = null; + StackTrace stackTrace = null; + + ApiException(this.code, this.message); + + ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); + + String toString() { + if (message == null) return "ApiException"; + + if (innerException == null) { + return "ApiException $code: $message"; + } + + return "ApiException $code: $message (Inner exception: ${innerException})\n\n" + + stackTrace.toString(); + } +} diff --git a/samples/client/petstore/dart/swagger/lib/api_helper.dart b/samples/client/petstore/dart/swagger/lib/api_helper.dart new file mode 100644 index 00000000000..ad73218ab40 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api_helper.dart @@ -0,0 +1,33 @@ +part of swagger.api; + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +Iterable _convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = []; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, '$value')); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, '$v')); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} diff --git a/samples/client/petstore/dart/swagger/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/swagger/lib/auth/api_key_auth.dart new file mode 100644 index 00000000000..d46fa15e9b8 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/auth/api_key_auth.dart @@ -0,0 +1,27 @@ +part of swagger.api; + +class ApiKeyAuth implements Authentication { + + final String location; + final String paramName; + String apiKey; + String apiKeyPrefix; + + ApiKeyAuth(this.location, this.paramName); + + @override + void applyToParams(List queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = '$apiKeyPrefix $apiKey'; + } else { + value = apiKey; + } + + if (location == 'query' && value != null) { + queryParams.add(new QueryParam(paramName, value)); + } else if (location == 'header' && value != null) { + headerParams[paramName] = value; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/dart/swagger/lib/auth/authentication.dart b/samples/client/petstore/dart/swagger/lib/auth/authentication.dart new file mode 100644 index 00000000000..3d6b6aadcda --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/auth/authentication.dart @@ -0,0 +1,7 @@ +part of swagger.api; + +abstract class Authentication { + + /// Apply authentication settings to header and query params. + void applyToParams(List queryParams, Map headerParams); +} \ No newline at end of file diff --git a/samples/client/petstore/dart/swagger/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/swagger/lib/auth/http_basic_auth.dart new file mode 100644 index 00000000000..7a118d6cdad --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/auth/http_basic_auth.dart @@ -0,0 +1,14 @@ +part of swagger.api; + +class HttpBasicAuth implements Authentication { + + String username; + String password; + + @override + void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str)); + } + +} \ No newline at end of file diff --git a/samples/client/petstore/dart/swagger/lib/auth/oauth.dart b/samples/client/petstore/dart/swagger/lib/auth/oauth.dart new file mode 100644 index 00000000000..405c5119a45 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/auth/oauth.dart @@ -0,0 +1,9 @@ +part of swagger.api; + +class OAuth implements Authentication { + + @override + void applyToParams(List queryParams, Map headerParams) { + // TODO: support oauth + } +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/model/api_response.dart b/samples/client/petstore/dart/swagger/lib/model/api_response.dart similarity index 93% rename from samples/client/petstore/dart/lib/model/api_response.dart rename to samples/client/petstore/dart/swagger/lib/model/api_response.dart index e8ffe737861..b2ac2c2577e 100644 --- a/samples/client/petstore/dart/lib/model/api_response.dart +++ b/samples/client/petstore/dart/swagger/lib/model/api_response.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/category.dart b/samples/client/petstore/dart/swagger/lib/model/category.dart similarity index 91% rename from samples/client/petstore/dart/lib/model/category.dart rename to samples/client/petstore/dart/swagger/lib/model/category.dart index e39966555fb..9ab2a96fc37 100644 --- a/samples/client/petstore/dart/lib/model/category.dart +++ b/samples/client/petstore/dart/swagger/lib/model/category.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/order.dart b/samples/client/petstore/dart/swagger/lib/model/order.dart similarity index 96% rename from samples/client/petstore/dart/lib/model/order.dart rename to samples/client/petstore/dart/swagger/lib/model/order.dart index 1d908629b06..d7ea97b3bad 100644 --- a/samples/client/petstore/dart/lib/model/order.dart +++ b/samples/client/petstore/dart/swagger/lib/model/order.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/pet.dart b/samples/client/petstore/dart/swagger/lib/model/pet.dart similarity index 96% rename from samples/client/petstore/dart/lib/model/pet.dart rename to samples/client/petstore/dart/swagger/lib/model/pet.dart index 8ad328b78be..03e13743763 100644 --- a/samples/client/petstore/dart/lib/model/pet.dart +++ b/samples/client/petstore/dart/swagger/lib/model/pet.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/tag.dart b/samples/client/petstore/dart/swagger/lib/model/tag.dart similarity index 91% rename from samples/client/petstore/dart/lib/model/tag.dart rename to samples/client/petstore/dart/swagger/lib/model/tag.dart index 0541e12fb6f..485de92a615 100644 --- a/samples/client/petstore/dart/lib/model/tag.dart +++ b/samples/client/petstore/dart/swagger/lib/model/tag.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/user.dart b/samples/client/petstore/dart/swagger/lib/model/user.dart similarity index 97% rename from samples/client/petstore/dart/lib/model/user.dart rename to samples/client/petstore/dart/swagger/lib/model/user.dart index fd99a51ee58..f529d9432c1 100644 --- a/samples/client/petstore/dart/lib/model/user.dart +++ b/samples/client/petstore/dart/swagger/lib/model/user.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/swagger/pubspec.yaml b/samples/client/petstore/dart/swagger/pubspec.yaml new file mode 100644 index 00000000000..e74546ea210 --- /dev/null +++ b/samples/client/petstore/dart/swagger/pubspec.yaml @@ -0,0 +1,14 @@ +name: swagger +version: 1.0.0 +description: Swagger API client +dependencies: + http: '>=0.11.1 <0.12.0' + dartson: "^0.2.4" + intl: "^0.12.4+2" + +dev_dependencies: + guinness: '^0.1.17' + browser: any + +transformers: + - dartson diff --git a/samples/client/petstore/dart/test/packages b/samples/client/petstore/dart/test/packages deleted file mode 120000 index a16c4050155..00000000000 --- a/samples/client/petstore/dart/test/packages +++ /dev/null @@ -1 +0,0 @@ -../packages \ No newline at end of file diff --git a/samples/client/petstore/dart/test/pet_test.dart b/samples/client/petstore/dart/test/pet_test.dart deleted file mode 100644 index f93c3ea3e37..00000000000 --- a/samples/client/petstore/dart/test/pet_test.dart +++ /dev/null @@ -1,85 +0,0 @@ -part of tests; - -testPetApi() { - var petApi = new PetApi(); - - describe('Pet API ', () { - it('adds a new pet and gets it by id', () async { - var id = 137; - - await petApi.addPet(new Pet()..id = id); - var pet = await petApi.getPetById(id); - expect(pet.id).toEqual(id); - }); - - it('doesn\'t get non-existing pet by id', () { - expect(petApi.getPetById(6789099)).toThrowWith(anInstanceOf: ApiException); - }); - - it('deletes existing pet by id', () async { - var id = 7689; - await petApi.addPet(new Pet()..id = id); - await petApi.deletePet(id, 'special-key'); - expect(petApi.getPetById(id)).toThrowWith(anInstanceOf: ApiException); - }); - - it('updates pet with form', () async { - var id = 52341; - await petApi.addPet(new Pet()..id = id..name='Snowy'); - await petApi.updatePetWithForm('$id', 'Doge', ''); - var pet = await petApi.getPetById(id); - expect(pet.name).toEqual('Doge'); - }); - - it('updates existing pet', () async { - var id = 900001; - var name = 'Snowy'; - - await petApi.addPet(new Pet()..id = id); - await petApi.updatePet(new Pet()..id = id..name = name); - var pet = await petApi.getPetById(id); - expect(pet.name).toEqual(name); - }); - - it('finds pets by status', () async { - var id1 = 754111; - var id2 = 1231341; - var id3 = 6776251; - var status = 'available'; - - return Future.wait([petApi.addPet(new Pet()..id = id1..status = status), - petApi.addPet(new Pet()..id = id2..status = status), - petApi.addPet(new Pet()..id = id3..status = 'sold')]) - .then((_) async { - - var pets = await petApi.findPetsByStatus([status]); - var petIds = pets.map((pet) => pet.id).toList(); - expect(petIds).toContain(id1); - expect(petIds).toContain(id2); - expect(petIds).not.toContain(id3); - }); - }); - - it('finds pets by tag', () async { - var snowyId = 253156; - var grumpyId = 734215; - var snowyTags = [new Tag()..id=12211..name='terrier']; - var grumpyTags = [new Tag()..id=455803..name='grumpy']; - await petApi.addPet(new Pet()..id = snowyId..name = 'Snowy'..tags = snowyTags); - await petApi.addPet(new Pet()..id = grumpyId..name = 'Grumpy Cat'..tags = grumpyTags); - - var pets = await petApi.findPetsByTags(['grumpy']); - var petIds = pets.map((pet) => pet.id).toList(); - expect(petIds).toContain(grumpyId); - expect(petIds).not.toContain(snowyId); - }); - - it('uploads a pet image', () async { - var id = 672322; - await petApi.addPet(new Pet()..id = id); - var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, '', file); - }); - - }); -} \ No newline at end of file diff --git a/samples/client/petstore/dart/test/store_test.dart b/samples/client/petstore/dart/test/store_test.dart deleted file mode 100644 index 692760f1be1..00000000000 --- a/samples/client/petstore/dart/test/store_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -part of tests; - -testStoreApi() { - var storeApi = new StoreApi(); - - describe('Store API ', () async { - - it('places an order and gets it by id', () async { - var id = 4356; - - await storeApi.placeOrder(new Order()..id = id); - var order = await storeApi.getOrderById(id.toString()); - expect(order.id).toEqual(id); - }); - - it('deletes an order', () async { - var id = 637211; - - await storeApi.placeOrder(new Order()..id = id); - await storeApi.deleteOrder(id.toString()); - expect(storeApi.getOrderById(id.toString())).toThrowWith(anInstanceOf: ApiException); - }); - - it('gets the store inventory', () async { - Map inventory = await storeApi.getInventory(); - expect(inventory.length).not.toBe(0); - }); - - }); -} \ No newline at end of file diff --git a/samples/client/petstore/dart/test/tests.dart b/samples/client/petstore/dart/test/tests.dart deleted file mode 100644 index 173a5587a4d..00000000000 --- a/samples/client/petstore/dart/test/tests.dart +++ /dev/null @@ -1,16 +0,0 @@ -library tests; - -import 'dart:async'; -import 'package:http/http.dart'; -import 'package:guinness/guinness.dart'; -import 'package:swagger/api.dart'; - -part 'pet_test.dart'; -part 'store_test.dart'; -part 'user_test.dart'; - -main() { - testPetApi(); - testStoreApi(); - testUserApi(); -} \ No newline at end of file diff --git a/samples/client/petstore/dart/test/user_test.dart b/samples/client/petstore/dart/test/user_test.dart deleted file mode 100644 index 886a6bc3c5d..00000000000 --- a/samples/client/petstore/dart/test/user_test.dart +++ /dev/null @@ -1,63 +0,0 @@ -part of tests; - -testUserApi() { - var userApi = new UserApi(); - - describe('User API ', () { - - it('creates a user', () async { - var id = 67567; - var username = 'Mally45'; - await userApi.createUser(new User()..id = id..username = username); - var user = await userApi.getUserByName(username); - expect(user.id).toEqual(id); - }); - - it('creates users with list input', () async { - var firstId = 46226; - var joe ='Joe'; - - var sally = 'Sally'; - var secondId = 95239; - - var users = [ new User()..id = firstId..username = joe, - new User()..id = secondId..username = sally]; - - await userApi.createUsersWithListInput(users); - var firstUser = await userApi.getUserByName(joe); - var secondUser = await userApi.getUserByName(sally); - expect(firstUser.id).toEqual(firstId); - expect(secondUser.id).toEqual(secondId); - }); - - it('updates a user', () async { - var username ='Arkjam89'; - var email = 'test@example.com'; - var user = new User()..id = 733356..username = username; - - await userApi.createUser(user); - user.email = email; - await userApi.updateUser(username,user); - var foundUser = await userApi.getUserByName(username); - expect(foundUser.email).toEqual(email); - }); - - it('deletes a user', () async { - var username ='Riddlem325'; - await userApi.createUser(new User()..id = 1231114..username = username); - await userApi.deleteUser(username); - expect(userApi.getUserByName(username)).toThrowWith(anInstanceOf: ApiException); - }); - - it('logs a user in', () async { - var username ='sgarad625'; - var password = 'lokimoki1'; - var user = new User()..id = 733356..username = username..password = password; - - await userApi.createUser(user); - var result = await userApi.loginUser(username, password); - expect(result).toContain('logged in user session:'); - }); - - }); -} \ No newline at end of file diff --git a/samples/client/petstore/flash/flash/build.properties b/samples/client/petstore/flash/flash/build.properties index 8e77d88c961..356f112b144 100644 --- a/samples/client/petstore/flash/flash/build.properties +++ b/samples/client/petstore/flash/flash/build.properties @@ -4,7 +4,7 @@ title=Sample app AS3 SDK API Documentation #Path to the source folder where the .as files are located sourcepath = ./src/main/flex -# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ ) +# Class-folders you want to search for classes to be included in the docs, separated by spaces (for example ../com/ ../net/ ) # to include every .as and .mxml file within your project, just state ../ domainextensions = ./src/main/flex diff --git a/samples/client/petstore/flash/flash/build.xml b/samples/client/petstore/flash/flash/build.xml index 4f021b0b8b2..9b84a466b76 100644 --- a/samples/client/petstore/flash/flash/build.xml +++ b/samples/client/petstore/flash/flash/build.xml @@ -17,7 +17,7 @@ - + diff --git a/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as b/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as index a43b7980a38..d19dd0ae358 100644 --- a/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as +++ b/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as @@ -12,7 +12,7 @@ public class Response { public var isSuccess:Boolean; /** - * The payload of the succesful operation eg. a Word in a WordRequest + * The payload of the successful operation eg. a Word in a WordRequest */ public var payload:Object; diff --git a/samples/client/petstore/flash/src/main/flex/build.properties b/samples/client/petstore/flash/src/main/flex/build.properties index 8e77d88c961..356f112b144 100644 --- a/samples/client/petstore/flash/src/main/flex/build.properties +++ b/samples/client/petstore/flash/src/main/flex/build.properties @@ -4,7 +4,7 @@ title=Sample app AS3 SDK API Documentation #Path to the source folder where the .as files are located sourcepath = ./src/main/flex -# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ ) +# Class-folders you want to search for classes to be included in the docs, separated by spaces (for example ../com/ ../net/ ) # to include every .as and .mxml file within your project, just state ../ domainextensions = ./src/main/flex diff --git a/samples/client/petstore/flash/src/main/flex/build.xml b/samples/client/petstore/flash/src/main/flex/build.xml index 4f021b0b8b2..9b84a466b76 100644 --- a/samples/client/petstore/flash/src/main/flex/build.xml +++ b/samples/client/petstore/flash/src/main/flex/build.xml @@ -17,7 +17,7 @@ - + diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as index a43b7980a38..d19dd0ae358 100644 --- a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as @@ -12,7 +12,7 @@ public class Response { public var isSuccess:Boolean; /** - * The payload of the succesful operation eg. a Word in a WordRequest + * The payload of the successful operation eg. a Word in a WordRequest */ public var payload:Object; diff --git a/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore b/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore +++ b/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 5d6a957aa1e..164eaf91c07 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -1,13 +1,12 @@ # Go API client for 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. +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 API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-26T21:47:25.590-07:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation @@ -22,6 +21,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **Patch** /fake | To test \"client\" model +*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **Post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **Get** /fake | To test enum parameters *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 @@ -46,10 +48,33 @@ Class | Method | HTTP request | Description ## 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) + - [Cat](docs/Cat.md) - [Category](docs/Category.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.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) - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) - [User](docs/User.md) @@ -57,6 +82,16 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## http_basic_test + +- **Type**: HTTP basic authentication + ## petstore_auth - **Type**: OAuth @@ -66,12 +101,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/go/go-petstore/additional_properties_class.go b/samples/client/petstore/go/go-petstore/additional_properties_class.go new file mode 100644 index 00000000000..ad768d2e478 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/additional_properties_class.go @@ -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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type AdditionalPropertiesClass struct { + + MapProperty map[string]string `json:"map_property,omitempty"` + + MapOfMapProperty map[string]map[string]string `json:"map_of_map_property,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/animal.go b/samples/client/petstore/go/go-petstore/animal.go new file mode 100644 index 00000000000..bc9d8161db7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/animal.go @@ -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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Animal struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/animal_farm.go b/samples/client/petstore/go/go-petstore/animal_farm.go new file mode 100644 index 00000000000..a412cbcd450 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/animal_farm.go @@ -0,0 +1,26 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type AnimalFarm struct { +} diff --git a/samples/client/petstore/go/go-petstore/api_client.go b/samples/client/petstore/go/go-petstore/api_client.go index 132ca3949fb..6196eb5a706 100644 --- a/samples/client/petstore/go/go-petstore/api_client.go +++ b/samples/client/petstore/go/go-petstore/api_client.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -29,10 +29,12 @@ import ( "reflect" "strings" "net/url" + "io/ioutil" "github.com/go-resty/resty" ) type APIClient struct { + config *Configuration } func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { @@ -57,9 +59,9 @@ func (c *APIClient) SelectHeaderAccept(accepts []string) string { return strings.Join(accepts, ",") } -func contains(source []string, containvalue string) bool { - for _, a := range source { - if strings.ToLower(a) == strings.ToLower(containvalue) { +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { return true } } @@ -74,11 +76,8 @@ func (c *APIClient) CallAPI(path string, method string, fileName string, fileBytes []byte) (*resty.Response, error) { - //set debug flag - configuration := NewConfiguration() - resty.SetDebug(configuration.GetDebug()) - - request := prepareRequest(postBody, headerParams, queryParams, formParams, fileName, fileBytes) + rClient := c.prepareClient() + request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) switch strings.ToUpper(method) { case "GET": @@ -115,19 +114,42 @@ func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) s } } - return obj.(string) + return fmt.Sprintf("%v", obj) +} + +func (c *APIClient) prepareClient() *resty.Client { + + rClient := resty.New() + + rClient.SetDebug(c.config.Debug) + if c.config.Transport != nil { + rClient.SetTransport(c.config.Transport) + } + + if c.config.Timeout != nil { + rClient.SetTimeout(*c.config.Timeout) + } + rClient.SetLogger(ioutil.Discard) + return rClient } -func prepareRequest(postBody interface{}, +func (c *APIClient) prepareRequest( + rClient *resty.Client, + postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams map[string]string, fileName string, fileBytes []byte) *resty.Request { - request := resty.R() + + request := rClient.R() request.SetBody(postBody) + if c.config.UserAgent != "" { + request.SetHeader("User-Agent", c.config.UserAgent) + } + // add header parameter, if any if len(headerParams) > 0 { request.SetHeaders(headerParams) diff --git a/samples/client/petstore/go/go-petstore/api_response.go b/samples/client/petstore/go/go-petstore/api_response.go index 57b94271eae..2459f617a03 100644 --- a/samples/client/petstore/go/go-petstore/api_response.go +++ b/samples/client/petstore/go/go-petstore/api_response.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -27,8 +27,20 @@ import ( ) type APIResponse struct { - *http.Response + *http.Response `json:"-"` Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { diff --git a/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go b/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go new file mode 100644 index 00000000000..8fc05e77a16 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayOfArrayOfNumberOnly struct { + + ArrayArrayNumber [][]float32 `json:"ArrayArrayNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/array_of_number_only.go b/samples/client/petstore/go/go-petstore/array_of_number_only.go new file mode 100644 index 00000000000..d9ef9a4c6d9 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_of_number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayOfNumberOnly struct { + + ArrayNumber []float32 `json:"ArrayNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/array_test.go b/samples/client/petstore/go/go-petstore/array_test.go new file mode 100644 index 00000000000..251f0a88efb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_test.go @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayTest struct { + + ArrayOfString []string `json:"array_of_string,omitempty"` + + ArrayArrayOfInteger [][]int64 `json:"array_array_of_integer,omitempty"` + + ArrayArrayOfModel [][]ReadOnlyFirst `json:"array_array_of_model,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/cat.go b/samples/client/petstore/go/go-petstore/cat.go new file mode 100644 index 00000000000..f8526999824 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/cat.go @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Cat struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` + + Declawed bool `json:"declawed,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/category.go b/samples/client/petstore/go/go-petstore/category.go index b8591811511..e33619f2fee 100644 --- a/samples/client/petstore/go/go-petstore/category.go +++ b/samples/client/petstore/go/go-petstore/category.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/go/go-petstore/client.go b/samples/client/petstore/go/go-petstore/client.go new file mode 100644 index 00000000000..e20c597d838 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/client.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Client struct { + + Client string `json:"client,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/configuration.go b/samples/client/petstore/go/go-petstore/configuration.go index 2bba74c7f53..549d4b7127c 100644 --- a/samples/client/petstore/go/go-petstore/configuration.go +++ b/samples/client/petstore/go/go-petstore/configuration.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -24,36 +24,42 @@ package petstore import ( "encoding/base64" + "net/http" + "time" ) + type Configuration struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` APIKey map[string]string `json:"APIKey,omitempty"` - debug bool `json:"debug,omitempty"` + Debug bool `json:"debug,omitempty"` DebugFile string `json:"debugFile,omitempty"` OAuthToken string `json:"oAuthToken,omitempty"` - Timeout int `json:"timeout,omitempty"` BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` AccessToken string `json:"accessToken,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` - APIClient APIClient `json:"APIClient,omitempty"` + APIClient *APIClient + Transport *http.Transport + Timeout *time.Duration `json:"timeout,omitempty"` } func NewConfiguration() *Configuration { - return &Configuration{ + cfg := &Configuration{ BasePath: "http://petstore.swagger.io/v2", - UserName: "", - debug: false, DefaultHeader: make(map[string]string), APIKey: make(map[string]string), APIKeyPrefix: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", + APIClient: &APIClient{}, } + + cfg.APIClient.config = cfg + return cfg } func (c *Configuration) GetBasicAuthEncodedString() string { @@ -71,11 +77,3 @@ func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { return c.APIKey[APIKeyIdentifier] } - -func (c *Configuration) SetDebug(enable bool) { - c.debug = enable -} - -func (c *Configuration) GetDebug() bool { - return c.debug -} diff --git a/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md b/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..abdb42c8e01 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapProperty** | **map[string]string** | | [optional] [default to null] +**MapOfMapProperty** | [**map[string]map[string]string**](map.md) | | [optional] [default to null] + +[[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/go/go-petstore/docs/Animal.md b/samples/client/petstore/go/go-petstore/docs/Animal.md new file mode 100644 index 00000000000..e7163af792c --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/AnimalFarm.md b/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..495038e58e1 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | [**[][]float32**](array.md) | | [optional] [default to null] + +[[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/go/go-petstore/docs/ArrayOfNumberOnly.md b/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..bd7a48160d2 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **[]float32** | | [optional] [default to null] + +[[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/go/go-petstore/docs/ArrayTest.md b/samples/client/petstore/go/go-petstore/docs/ArrayTest.md new file mode 100644 index 00000000000..6cf88880292 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayOfString** | **[]string** | | [optional] [default to null] +**ArrayArrayOfInteger** | [**[][]int64**](array.md) | | [optional] [default to null] +**ArrayArrayOfModel** | [**[][]ReadOnlyFirst**](array.md) | | [optional] [default to null] + +[[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/go/go-petstore/docs/Cat.md b/samples/client/petstore/go/go-petstore/docs/Cat.md new file mode 100644 index 00000000000..3a49c3ca62e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Cat.md @@ -0,0 +1,12 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] +**Declawed** | **bool** | | [optional] [default to null] + +[[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/go/go-petstore/docs/Client.md b/samples/client/petstore/go/go-petstore/docs/Client.md new file mode 100644 index 00000000000..d8edb814853 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Client** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/Dog.md b/samples/client/petstore/go/go-petstore/docs/Dog.md new file mode 100644 index 00000000000..7178972d5dc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Dog.md @@ -0,0 +1,12 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] +**Breed** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/EnumArrays.md b/samples/client/petstore/go/go-petstore/docs/EnumArrays.md new file mode 100644 index 00000000000..2ca85fdd1fb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustSymbol** | **string** | | [optional] [default to null] +**ArrayEnum** | **[]string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/EnumClass.md b/samples/client/petstore/go/go-petstore/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumTest.md b/samples/client/petstore/go/go-petstore/docs/EnumTest.md new file mode 100644 index 00000000000..fe6ca0cb32d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] [default to null] +**EnumInteger** | **int32** | | [optional] [default to null] +**EnumNumber** | **float64** | | [optional] [default to null] + +[[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/go/go-petstore/docs/FakeApi.md b/samples/client/petstore/go/go-petstore/docs/FakeApi.md new file mode 100644 index 00000000000..63e7fb728fb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/FakeApi.md @@ -0,0 +1,113 @@ +# \FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +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 + + +# **TestClientModel** +> Client TestClientModel($body) + +To test \"client\" model + + +### 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 + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestEndpointParameters** +> TestEndpointParameters($number, $double, $patternWithoutDelimiter, $byte_, $integer, $int32_, $int64_, $float, $string_, $binary, $date, $dateTime, $password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float32**| None | + **double** | **float64**| None | + **patternWithoutDelimiter** | **string**| None | + **byte_** | **string**| None | + **integer** | **int32**| None | [optional] + **int32_** | **int32**| None | [optional] + **int64_** | **int64**| None | [optional] + **float** | **float32**| None | [optional] + **string_** | **string**| None | [optional] + **binary** | **string**| None | [optional] + **date** | **time.Time**| None | [optional] + **dateTime** | **time.Time**| None | [optional] + **password** | **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** +> TestEnumParameters($enumFormStringArray, $enumFormString, $enumHeaderStringArray, $enumHeaderString, $enumQueryStringArray, $enumQueryString, $enumQueryInteger, $enumQueryDouble) + +To test enum parameters + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**[]string**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**[]string**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**[]string**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enumQueryInteger** | **float32**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **float64**| Query parameter enum test (double) | [optional] + +### Return type + +void (empty response body) + +### 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/go/go-petstore/docs/FormatTest.md b/samples/client/petstore/go/go-petstore/docs/FormatTest.md new file mode 100644 index 00000000000..05f41a8039f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Integer** | **int32** | | [optional] [default to null] +**Int32_** | **int32** | | [optional] [default to null] +**Int64_** | **int64** | | [optional] [default to null] +**Number** | **float32** | | [default to null] +**Float** | **float32** | | [optional] [default to null] +**Double** | **float64** | | [optional] [default to null] +**String_** | **string** | | [optional] [default to null] +**Byte_** | **string** | | [default to null] +**Binary** | **string** | | [optional] [default to null] +**Date** | [**time.Time**](time.Time.md) | | [default to null] +**DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**Uuid** | **string** | | [optional] [default to null] +**Password** | **string** | | [default to null] + +[[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/go/go-petstore/docs/HasOnlyReadOnly.md b/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..32dfdedcfe7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to null] +**Foo** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/List.md b/samples/client/petstore/go/go-petstore/docs/List.md new file mode 100644 index 00000000000..54fd3876c26 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Var123List** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/MapTest.md b/samples/client/petstore/go/go-petstore/docs/MapTest.md new file mode 100644 index 00000000000..6b70bf448e8 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/MapTest.md @@ -0,0 +1,11 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | [**map[string]map[string]string**](map.md) | | [optional] [default to null] +**MapOfEnumString** | **map[string]string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..b4de97169dd --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **string** | | [optional] [default to null] +**DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**Map_** | [**map[string]Animal**](Animal.md) | | [optional] [default to null] + +[[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/go/go-petstore/docs/Model200Response.md b/samples/client/petstore/go/go-petstore/docs/Model200Response.md new file mode 100644 index 00000000000..8b4bb38033d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int32** | | [optional] [default to null] +**Class** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/ModelReturn.md b/samples/client/petstore/go/go-petstore/docs/ModelReturn.md new file mode 100644 index 00000000000..86350d4310c --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Return_** | **int32** | | [optional] [default to null] + +[[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/go/go-petstore/docs/Name.md b/samples/client/petstore/go/go-petstore/docs/Name.md new file mode 100644 index 00000000000..d677e60263f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int32** | | [default to null] +**SnakeCase** | **int32** | | [optional] [default to null] +**Property** | **string** | | [optional] [default to null] +**Var123Number** | **int32** | | [optional] [default to null] + +[[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/go/go-petstore/docs/NumberOnly.md b/samples/client/petstore/go/go-petstore/docs/NumberOnly.md new file mode 100644 index 00000000000..3ebbf2f0308 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **float32** | | [optional] [default to null] + +[[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/go/go-petstore/docs/ReadOnlyFirst.md b/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..3ff591d7a74 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to null] +**Baz** | **string** | | [optional] [default to null] + +[[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/go/go-petstore/docs/SpecialModelName.md b/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md new file mode 100644 index 00000000000..dcf601a308d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SpecialPropertyName** | **int64** | | [optional] [default to null] + +[[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/go/go-petstore/dog.go b/samples/client/petstore/go/go-petstore/dog.go new file mode 100644 index 00000000000..acf4999618e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/dog.go @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Dog struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` + + Breed string `json:"breed,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/enum_arrays.go b/samples/client/petstore/go/go-petstore/enum_arrays.go new file mode 100644 index 00000000000..3b42ad142b5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_arrays.go @@ -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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumArrays struct { + + JustSymbol string `json:"just_symbol,omitempty"` + + ArrayEnum []string `json:"array_enum,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/enum_class.go b/samples/client/petstore/go/go-petstore/enum_class.go new file mode 100644 index 00000000000..4a63f179dd3 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_class.go @@ -0,0 +1,26 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumClass struct { +} diff --git a/samples/client/petstore/go/go-petstore/enum_test.go b/samples/client/petstore/go/go-petstore/enum_test.go new file mode 100644 index 00000000000..c2be92c6246 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_test.go @@ -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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumTest struct { + + EnumString string `json:"enum_string,omitempty"` + + EnumInteger int32 `json:"enum_integer,omitempty"` + + EnumNumber float64 `json:"enum_number,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/fake_api.go b/samples/client/petstore/go/go-petstore/fake_api.go new file mode 100644 index 00000000000..f7cb65af821 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/fake_api.go @@ -0,0 +1,282 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "net/url" + "strings" + "time" + "encoding/json" +) + +type FakeApi struct { + Configuration *Configuration +} + +func NewFakeApi() *FakeApi { + configuration := NewConfiguration() + return &FakeApi{ + Configuration: configuration, + } +} + +func NewFakeApiWithBasePath(basePath string) *FakeApi { + configuration := NewConfiguration() + configuration.BasePath = basePath + + return &FakeApi{ + Configuration: configuration, + } +} + +/** + * To test \"client\" model + * + * @param body client model + * @return *Client + */ +func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Patch") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + var successPayload = new(Client) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "TestClientModel", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + + if err != nil { + return successPayload, localVarAPIResponse, err + } + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err +} + +/** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @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 + * @return void + */ +func (a FakeApi) TestEndpointParameters(number float32, double float64, patternWithoutDelimiter string, byte_ string, integer int32, int32_ int32, int64_ int64, float float32, string_ string, binary string, date time.Time, dateTime time.Time, password string) (*APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Post") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(http_basic_test)' required + // http basic authentication required + if a.Configuration.UserName != "" || a.Configuration.Password != ""{ + localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() + } + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/xml; charset=utf-8", "application/json; charset=utf-8", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/xml; charset=utf-8", + "application/json; charset=utf-8", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + localVarFormParams["integer"] = a.Configuration.APIClient.ParameterToString(integer, "") + localVarFormParams["int32_"] = a.Configuration.APIClient.ParameterToString(int32_, "") + localVarFormParams["int64_"] = a.Configuration.APIClient.ParameterToString(int64_, "") + localVarFormParams["number"] = a.Configuration.APIClient.ParameterToString(number, "") + localVarFormParams["float"] = a.Configuration.APIClient.ParameterToString(float, "") + localVarFormParams["double"] = a.Configuration.APIClient.ParameterToString(double, "") + localVarFormParams["string_"] = a.Configuration.APIClient.ParameterToString(string_, "") + localVarFormParams["patternWithoutDelimiter"] = a.Configuration.APIClient.ParameterToString(patternWithoutDelimiter, "") + localVarFormParams["byte_"] = a.Configuration.APIClient.ParameterToString(byte_, "") + localVarFormParams["binary"] = a.Configuration.APIClient.ParameterToString(binary, "") + localVarFormParams["date"] = a.Configuration.APIClient.ParameterToString(date, "") + localVarFormParams["dateTime"] = a.Configuration.APIClient.ParameterToString(dateTime, "") + localVarFormParams["password"] = a.Configuration.APIClient.ParameterToString(password, "") + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "TestEndpointParameters", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + + if err != nil { + return localVarAPIResponse, err + } + return localVarAPIResponse, err +} + +/** + * To test enum parameters + * + * @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) + * @return void + */ +func (a FakeApi) TestEnumParameters(enumFormStringArray []string, enumFormString string, enumHeaderStringArray []string, enumHeaderString string, enumQueryStringArray []string, enumQueryString string, enumQueryInteger float32, enumQueryDouble float64) (*APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Get") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + var collectionFormat = "csv" + if collectionFormat == "multi" { + for _, value := range enumQueryStringArray { + localVarQueryParams.Add("enum_query_string_array", value) + } + } else { + localVarQueryParams.Add("enum_query_string_array", a.Configuration.APIClient.ParameterToString(enumQueryStringArray, collectionFormat)) + } + localVarQueryParams.Add("enum_query_string", a.Configuration.APIClient.ParameterToString(enumQueryString, "")) + localVarQueryParams.Add("enum_query_integer", a.Configuration.APIClient.ParameterToString(enumQueryInteger, "")) + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // header params "enum_header_string_array" + localVarHeaderParams["enum_header_string_array"] = a.Configuration.APIClient.ParameterToString(enumHeaderStringArray, "") + // header params "enum_header_string" + localVarHeaderParams["enum_header_string"] = a.Configuration.APIClient.ParameterToString(enumHeaderString, "") + localVarFormParams["enumFormStringArray"] = a.Configuration.APIClient.ParameterToString(enumFormStringArray, "") + localVarFormParams["enumFormString"] = a.Configuration.APIClient.ParameterToString(enumFormString, "") + localVarFormParams["enumQueryDouble"] = a.Configuration.APIClient.ParameterToString(enumQueryDouble, "") + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "TestEnumParameters", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + + if err != nil { + return localVarAPIResponse, err + } + return localVarAPIResponse, err +} + diff --git a/samples/client/petstore/go/go-petstore/format_test.go b/samples/client/petstore/go/go-petstore/format_test.go new file mode 100644 index 00000000000..fa370de4d12 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/format_test.go @@ -0,0 +1,56 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "time" +) + +type FormatTest struct { + + Integer int32 `json:"integer,omitempty"` + + Int32_ int32 `json:"int32,omitempty"` + + Int64_ int64 `json:"int64,omitempty"` + + Number float32 `json:"number,omitempty"` + + Float float32 `json:"float,omitempty"` + + Double float64 `json:"double,omitempty"` + + String_ string `json:"string,omitempty"` + + Byte_ string `json:"byte,omitempty"` + + Binary string `json:"binary,omitempty"` + + Date time.Time `json:"date,omitempty"` + + DateTime time.Time `json:"dateTime,omitempty"` + + Uuid string `json:"uuid,omitempty"` + + Password string `json:"password,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/has_only_read_only.go b/samples/client/petstore/go/go-petstore/has_only_read_only.go new file mode 100644 index 00000000000..f95600a35bc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/has_only_read_only.go @@ -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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type HasOnlyReadOnly struct { + + Bar string `json:"bar,omitempty"` + + Foo string `json:"foo,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/list.go b/samples/client/petstore/go/go-petstore/list.go new file mode 100644 index 00000000000..7fcab1a6d84 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/list.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type List struct { + + Var123List string `json:"123-list,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/map_test.go b/samples/client/petstore/go/go-petstore/map_test.go new file mode 100644 index 00000000000..88b060ef3c4 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/map_test.go @@ -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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type MapTest struct { + + MapMapOfString map[string]map[string]string `json:"map_map_of_string,omitempty"` + + MapOfEnumString map[string]string `json:"map_of_enum_string,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go b/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go new file mode 100644 index 00000000000..6a34a75cefc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go @@ -0,0 +1,36 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "time" +) + +type MixedPropertiesAndAdditionalPropertiesClass struct { + + Uuid string `json:"uuid,omitempty"` + + DateTime time.Time `json:"dateTime,omitempty"` + + Map_ map[string]Animal `json:"map,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/model_200_response.go b/samples/client/petstore/go/go-petstore/model_200_response.go new file mode 100644 index 00000000000..6fefe4b6ab7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/model_200_response.go @@ -0,0 +1,31 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing model name starting with number +type Model200Response struct { + + Name int32 `json:"name,omitempty"` + + Class string `json:"class,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/model_api_response.go b/samples/client/petstore/go/go-petstore/model_api_response.go index 85bba3df10e..8e0c191070e 100644 --- a/samples/client/petstore/go/go-petstore/model_api_response.go +++ b/samples/client/petstore/go/go-petstore/model_api_response.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/go/go-petstore/model_return.go b/samples/client/petstore/go/go-petstore/model_return.go new file mode 100644 index 00000000000..a2f3244ebf5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/model_return.go @@ -0,0 +1,29 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing reserved words +type ModelReturn struct { + + Return_ int32 `json:"return,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/name.go b/samples/client/petstore/go/go-petstore/name.go new file mode 100644 index 00000000000..6bde7a16d00 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/name.go @@ -0,0 +1,35 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing model name same as property name +type Name struct { + + Name int32 `json:"name,omitempty"` + + SnakeCase int32 `json:"snake_case,omitempty"` + + Property string `json:"property,omitempty"` + + Var123Number int32 `json:"123Number,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/number_only.go b/samples/client/petstore/go/go-petstore/number_only.go new file mode 100644 index 00000000000..96a0d7f2133 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type NumberOnly struct { + + JustNumber float32 `json:"JustNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/order.go b/samples/client/petstore/go/go-petstore/order.go index f5b83768175..f571d82c58b 100644 --- a/samples/client/petstore/go/go-petstore/order.go +++ b/samples/client/petstore/go/go-petstore/order.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/go/go-petstore/pet.go b/samples/client/petstore/go/go-petstore/pet.go index b230ea45dac..0a961ab3ea9 100644 --- a/samples/client/petstore/go/go-petstore/pet.go +++ b/samples/client/petstore/go/go-petstore/pet.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index 07dc51eb90e..bb89aea874d 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -23,23 +23,22 @@ package petstore import ( - "strings" - "fmt" - "errors" "net/url" + "strings" "os" -"io/ioutil" -"encoding/json" + "io/ioutil" + "encoding/json" + "fmt" ) type PetApi struct { - Configuration Configuration + Configuration *Configuration } func NewPetApi() *PetApi { configuration := NewConfiguration() return &PetApi{ - Configuration: *configuration, + Configuration: configuration, } } @@ -48,7 +47,7 @@ func NewPetApiWithBasePath(basePath string) *PetApi { configuration.BasePath = basePath return &PetApi{ - Configuration: *configuration, + Configuration: configuration, } } @@ -61,62 +60,61 @@ func NewPetApiWithBasePath(basePath string) *PetApi { */ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/pet" - - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling PetApi->AddPet") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "application/xml", } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body + localVarPostBody = &body + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "AddPet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -129,64 +127,62 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { */ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { - var httpMethod = "Delete" + var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables - path := a.Configuration.BasePath + "/pet/{petId}" - path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - - // verify the required parameter 'petId' is set - if &petId == nil { - return nil, errors.New("Missing required parameter 'petId' when calling PetApi->DeletePet") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet/{petId}" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - // header params "api_key" - headerParams["api_key"] = apiKey + localVarHeaderParams["api_key"] = a.Configuration.APIClient.ParameterToString(apiKey, "") + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "DeletePet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -198,40 +194,33 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { */ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/pet/findByStatus" - - // verify the required parameter 'status' is set - if &status == nil { - return *new([]Pet), nil, errors.New("Missing required parameter 'status' when calling PetApi->FindPetsByStatus") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet/findByStatus" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } var collectionFormat = "csv" if collectionFormat == "multi" { for _, value := range status { - queryParams.Add("status", value) + localVarQueryParams.Add("status", value) } } else { - queryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, collectionFormat)) + localVarQueryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, collectionFormat)) } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -239,26 +228,35 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new([]Pet) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "FindPetsByStatus", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return *successPayload, NewAPIResponse(httpResponse.RawResponse), err + return *successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return *successPayload, localVarAPIResponse, err } /** @@ -270,40 +268,33 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { */ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/pet/findByTags" - - // verify the required parameter 'tags' is set - if &tags == nil { - return *new([]Pet), nil, errors.New("Missing required parameter 'tags' when calling PetApi->FindPetsByTags") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet/findByTags" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } var collectionFormat = "csv" if collectionFormat == "multi" { for _, value := range tags { - queryParams.Add("tags", value) + localVarQueryParams.Add("tags", value) } } else { - queryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, collectionFormat)) + localVarQueryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, collectionFormat)) } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -311,26 +302,35 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new([]Pet) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "FindPetsByTags", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return *successPayload, NewAPIResponse(httpResponse.RawResponse), err + return *successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return *successPayload, localVarAPIResponse, err } /** @@ -342,59 +342,60 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { */ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/pet/{petId}" - path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - - // verify the required parameter 'petId' is set - if &petId == nil { - return new(Pet), nil, errors.New("Missing required parameter 'petId' when calling PetApi->GetPetById") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (api_key) required - + localVarPath := a.Configuration.BasePath + "/pet/{petId}" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(api_key)' required // set key with prefix in header - headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") - + localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new(Pet) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetPetById", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** @@ -406,62 +407,61 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { */ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { - var httpMethod = "Put" + var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - path := a.Configuration.BasePath + "/pet" - - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling PetApi->UpdatePet") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "application/xml", } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body + localVarPostBody = &body + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UpdatePet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -475,63 +475,62 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { */ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/pet/{petId}" - path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - - // verify the required parameter 'petId' is set - if &petId == nil { - return nil, errors.New("Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet/{petId}" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/x-www-form-urlencoded", } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } + localVarFormParams["name"] = a.Configuration.APIClient.ParameterToString(name, "") + localVarFormParams["status"] = a.Configuration.APIClient.ParameterToString(status, "") + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - formParams["name"] = name - formParams["status"] = status + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UpdatePetWithForm", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -545,64 +544,64 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API */ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File) (*ModelApiResponse, *APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/pet/{petId}/uploadImage" - path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - - // verify the required parameter 'petId' is set - if &petId == nil { - return new(ModelApiResponse), nil, errors.New("Missing required parameter 'petId' when calling PetApi->UploadFile") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (petstore_auth) required - + localVarPath := a.Configuration.BasePath + "/pet/{petId}/uploadImage" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ - headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ "multipart/form-data", } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", - } + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - - formParams["additionalMetadata"] = additionalMetadata + localVarFormParams["additionalMetadata"] = a.Configuration.APIClient.ParameterToString(additionalMetadata, "") fbs, _ := ioutil.ReadAll(file) - fileBytes = fbs - fileName = file.Name() - + localVarFileBytes = fbs + localVarFileName = file.Name() var successPayload = new(ModelApiResponse) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UploadFile", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } diff --git a/samples/client/petstore/go/go-petstore/read_only_first.go b/samples/client/petstore/go/go-petstore/read_only_first.go new file mode 100644 index 00000000000..9d8e6351fdf --- /dev/null +++ b/samples/client/petstore/go/go-petstore/read_only_first.go @@ -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 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ReadOnlyFirst struct { + + Bar string `json:"bar,omitempty"` + + Baz string `json:"baz,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/special_model_name.go b/samples/client/petstore/go/go-petstore/special_model_name.go new file mode 100644 index 00000000000..7bbb2093ef4 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/special_model_name.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type SpecialModelName struct { + + SpecialPropertyName int64 `json:"$special[property.name],omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index e2de74695ee..384fb351823 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -23,21 +23,20 @@ package petstore import ( - "strings" - "fmt" - "errors" "net/url" + "strings" "encoding/json" + "fmt" ) type StoreApi struct { - Configuration Configuration + Configuration *Configuration } func NewStoreApi() *StoreApi { configuration := NewConfiguration() return &StoreApi{ - Configuration: *configuration, + Configuration: configuration, } } @@ -46,7 +45,7 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi { configuration.BasePath = basePath return &StoreApi{ - Configuration: *configuration, + Configuration: configuration, } } @@ -59,55 +58,55 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi { */ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { - var httpMethod = "Delete" + var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables - path := a.Configuration.BasePath + "/store/order/{orderId}" - path = strings.Replace(path, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) - - // verify the required parameter 'orderId' is set - if &orderId == nil { - return nil, errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/store/order/{orderId}" + localVarPath = strings.Replace(localVarPath, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "DeleteOrder", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -118,53 +117,58 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { */ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/store/inventory" - - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - // authentication (api_key) required - + localVarPath := a.Configuration.BasePath + "/store/inventory" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(api_key)' required // set key with prefix in header - headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") - + localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", - } + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new(map[string]int32) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetInventory", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** @@ -176,55 +180,57 @@ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { */ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/store/order/{orderId}" - path = strings.Replace(path, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) - - // verify the required parameter 'orderId' is set - if &orderId == nil { - return new(Order), nil, errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/store/order/{orderId}" + localVarPath = strings.Replace(localVarPath, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new(Order) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetOrderById", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** @@ -236,56 +242,57 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { */ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/store/order" - - // verify the required parameter 'body' is set - if &body == nil { - return new(Order), nil, errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/store/order" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body - + localVarPostBody = &body var successPayload = new(Order) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "PlaceOrder", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } diff --git a/samples/client/petstore/go/go-petstore/tag.go b/samples/client/petstore/go/go-petstore/tag.go index 80d219bb36c..ab74301c5b1 100644 --- a/samples/client/petstore/go/go-petstore/tag.go +++ b/samples/client/petstore/go/go-petstore/tag.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/go/go-petstore/user.go b/samples/client/petstore/go/go-petstore/user.go index a2cc5850d75..cc1b040e801 100644 --- a/samples/client/petstore/go/go-petstore/user.go +++ b/samples/client/petstore/go/go-petstore/user.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 2cd9ed6605c..9ec01dd7b64 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -23,21 +23,20 @@ package petstore import ( - "strings" - "fmt" - "errors" "net/url" + "strings" "encoding/json" + "fmt" ) type UserApi struct { - Configuration Configuration + Configuration *Configuration } func NewUserApi() *UserApi { configuration := NewConfiguration() return &UserApi{ - Configuration: *configuration, + Configuration: configuration, } } @@ -46,7 +45,7 @@ func NewUserApiWithBasePath(basePath string) *UserApi { configuration.BasePath = basePath return &UserApi{ - Configuration: *configuration, + Configuration: configuration, } } @@ -59,57 +58,56 @@ func NewUserApiWithBasePath(basePath string) *UserApi { */ func (a UserApi) CreateUser(body User) (*APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/user" - - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUser") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body + localVarPostBody = &body + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "CreateUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -121,57 +119,56 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { */ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/user/createWithArray" - - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/createWithArray" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body + localVarPostBody = &body + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "CreateUsersWithArrayInput", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -183,57 +180,56 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { */ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { - var httpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - path := a.Configuration.BasePath + "/user/createWithList" - - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/createWithList" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body + localVarPostBody = &body + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "CreateUsersWithListInput", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -245,55 +241,55 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { */ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { - var httpMethod = "Delete" + var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables - path := a.Configuration.BasePath + "/user/{username}" - path = strings.Replace(path, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) - - // verify the required parameter 'username' is set - if &username == nil { - return nil, errors.New("Missing required parameter 'username' when calling UserApi->DeleteUser") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/{username}" + localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "DeleteUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(httpResponse.RawResponse), err + if err != nil { + return localVarAPIResponse, err + } + return localVarAPIResponse, err } /** @@ -305,55 +301,57 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { */ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/user/{username}" - path = strings.Replace(path, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) - - // verify the required parameter 'username' is set - if &username == nil { - return new(User), nil, errors.New("Missing required parameter 'username' when calling UserApi->GetUserByName") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/{username}" + localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new(User) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetUserByName", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** @@ -366,33 +364,22 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { */ func (a UserApi) LoginUser(username string, password string) (*string, *APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/user/login" - - // verify the required parameter 'username' is set - if &username == nil { - return new(string), nil, errors.New("Missing required parameter 'username' when calling UserApi->LoginUser") - } - // verify the required parameter 'password' is set - if &password == nil { - return new(string), nil, errors.New("Missing required parameter 'password' when calling UserApi->LoginUser") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/login" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - queryParams.Add("username", a.Configuration.APIClient.ParameterToString(username, "")) - queryParams.Add("password", a.Configuration.APIClient.ParameterToString(password, "")) - + localVarQueryParams.Add("username", a.Configuration.APIClient.ParameterToString(username, "")) + localVarQueryParams.Add("password", a.Configuration.APIClient.ParameterToString(password, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -400,26 +387,35 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } var successPayload = new(string) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "LoginUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + if err != nil { - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } - err = json.Unmarshal(httpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(httpResponse.RawResponse), err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** @@ -430,50 +426,54 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo */ func (a UserApi) LogoutUser() (*APIResponse, error) { - var httpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - path := a.Configuration.BasePath + "/user/logout" - - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/logout" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "LogoutUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(httpResponse.RawResponse), err + if err != nil { + return localVarAPIResponse, err + } + return localVarAPIResponse, err } /** @@ -486,61 +486,56 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { */ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { - var httpMethod = "Put" + var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - path := a.Configuration.BasePath + "/user/{username}" - path = strings.Replace(path, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) - - // verify the required parameter 'username' is set - if &username == nil { - return nil, errors.New("Missing required parameter 'username' when calling UserApi->UpdateUser") - } - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->UpdateUser") - } - - headerParams := make(map[string]string) - queryParams := url.Values{} - formParams := make(map[string]string) - var postBody interface{} - var fileName string - var fileBytes []byte - + localVarPath := a.Configuration.BasePath + "/user/{username}" + localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { - headerParams[key] = a.Configuration.DefaultHeader[key] + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { - headerParams["Content-Type"] = localVarHttpContentType + localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", -"application/json", - } + "application/json", + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { - headerParams["Accept"] = localVarHttpHeaderAccept + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params - postBody = &body + localVarPostBody = &body + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UpdateUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } - httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } - - return NewAPIResponse(httpResponse.RawResponse), err + return localVarAPIResponse, err } diff --git a/samples/client/petstore/go/pom.xml b/samples/client/petstore/go/pom.xml index 7ecbbc7e198..028ef60a6f4 100644 --- a/samples/client/petstore/go/pom.xml +++ b/samples/client/petstore/go/pom.xml @@ -4,7 +4,7 @@ Goswagger pom 1.0.0 - Goswagger + Go Petstore Client diff --git a/samples/client/petstore/groovy/.swagger-codegen-ignore b/samples/client/petstore/groovy/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/groovy/.swagger-codegen-ignore +++ b/samples/client/petstore/groovy/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/java/default/README.md b/samples/client/petstore/java/default/README.md deleted file mode 100644 index 562d76a8db4..00000000000 --- a/samples/client/petstore/java/default/README.md +++ /dev/null @@ -1,199 +0,0 @@ -# swagger-java-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-java-client - 1.0.0 - compile - -``` - -### Gradle users - -Add this dependency to your project's build file: - -```groovy -compile "io.swagger:swagger-java-client:1.0.0" -``` - -### Others - -At first generate the JAR by executing: - - mvn package - -Then manually install the following JARs: - -* target/swagger-java-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.PetApi; - -import java.io.File; -import java.util.*; - -public class PetApiExample { - - public static void main(String[] args) { - 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(); - } - } -} - -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**addPetUsingByteArray**](docs/PetApi.md#addPetUsingByteArray) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding 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* | [**getPetByIdInObject**](docs/PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -*PetApi* | [**petPetIdtestingByteArraytrueGet**](docs/PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' -*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status -*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' -*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user - - -## Documentation for Models - - - [Animal](docs/Animal.md) - - [Cat](docs/Cat.md) - - [Category](docs/Category.md) - - [Dog](docs/Dog.md) - - [InlineResponse200](docs/InlineResponse200.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Name](docs/Name.md) - - [Order](docs/Order.md) - - [Pet](docs/Pet.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [Tag](docs/Tag.md) - - [User](docs/User.md) - - -## Documentation for Authorization - -Authentication schemes defined for the API: -### petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - write:pets: modify pets in your account - - read:pets: read your pets - -### test_api_client_id - -- **Type**: API key -- **API key parameter name**: x-test_api_client_id -- **Location**: HTTP header - -### test_api_client_secret - -- **Type**: API key -- **API key parameter name**: x-test_api_client_secret -- **Location**: HTTP header - -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - -### test_http_basic - -- **Type**: HTTP basic authentication - -### test_api_key_query - -- **Type**: API key -- **API key parameter name**: test_api_key_query -- **Location**: URL query string - -### test_api_key_header - -- **Type**: API key -- **API key parameter name**: test_api_key_header -- **Location**: HTTP header - - -## Recommendation - -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. - -## Author - -apiteam@swagger.io - diff --git a/samples/client/petstore/java/default/build.gradle b/samples/client/petstore/java/default/build.gradle deleted file mode 100644 index 33ceee9bb95..00000000000 --- a/samples/client/petstore/java/default/build.gradle +++ /dev/null @@ -1,116 +0,0 @@ -apply plugin: 'idea' -apply plugin: 'eclipse' - -group = 'io.swagger' -version = '1.0.0' - -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:1.5.+' - classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' - } -} - -repositories { - jcenter() -} - - -if(hasProperty('target') && target == 'android') { - - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 23 - buildToolsVersion '23.0.2' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 23 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - - dependencies { - provided 'javax.annotation:jsr250-api:1.0' - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } - -} else { - - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-java-client' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } -} - -ext { - swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" - jersey_version = "1.19.1" - jodatime_version = "2.9.3" - junit_version = "4.12" -} - -dependencies { - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "com.sun.jersey:jersey-client:$jersey_version" - compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" - compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" - compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" - compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" - compile "joda-time:joda-time:$jodatime_version" - compile "com.brsanthu:migbase64:2.2" - testCompile "junit:junit:$junit_version" -} diff --git a/samples/client/petstore/java/default/docs/ApiResponse.md b/samples/client/petstore/java/default/docs/ApiResponse.md deleted file mode 100644 index 1c17767c2b7..00000000000 --- a/samples/client/petstore/java/default/docs/ApiResponse.md +++ /dev/null @@ -1,12 +0,0 @@ - -# ApiResponse - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] -**type** | **String** | | [optional] -**message** | **String** | | [optional] - - - diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/default/docs/FakeApi.md deleted file mode 100644 index 0c1f55a0902..00000000000 --- a/samples/client/petstore/java/default/docs/FakeApi.md +++ /dev/null @@ -1,75 +0,0 @@ -# FakeApi - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - - - -# **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.FakeApi; - - -FakeApi apiInstance = new FakeApi(); -BigDecimal number = new BigDecimal(); // BigDecimal | None -Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None -byte[] _byte = B; // byte[] | None -Integer integer = 56; // Integer | None -Integer int32 = 56; // Integer | None -Long int64 = 789L; // Long | None -Float _float = 3.4F; // Float | None -byte[] binary = B; // byte[] | None -LocalDate date = new LocalDate(); // LocalDate | None -DateTime dateTime = new DateTime(); // DateTime | None -String password = "password_example"; // String | None -try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); -} catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEndpointParameters"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **BigDecimal**| None | - **_double** | **Double**| None | - **string** | **String**| None | - **_byte** | **byte[]**| None | - **integer** | **Integer**| None | [optional] - **int32** | **Integer**| None | [optional] - **int64** | **Long**| None | [optional] - **_float** | **Float**| None | [optional] - **binary** | **byte[]**| None | [optional] - **date** | **LocalDate**| None | [optional] - **dateTime** | **DateTime**| None | [optional] - **password** | **String**| None | [optional] - -### Return type - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - diff --git a/samples/client/petstore/java/default/docs/InlineResponse200.md b/samples/client/petstore/java/default/docs/InlineResponse200.md deleted file mode 100644 index 487ebe429e4..00000000000 --- a/samples/client/petstore/java/default/docs/InlineResponse200.md +++ /dev/null @@ -1,24 +0,0 @@ - -# InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**photoUrls** | **List<String>** | | [optional] -**name** | **String** | | [optional] -**id** | **Long** | | -**category** | **Object** | | [optional] -**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/default/gradlew.bat b/samples/client/petstore/java/default/gradlew.bat deleted file mode 100644 index 72d362dafd8..00000000000 --- a/samples/client/petstore/java/default/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/client/petstore/java/default/hello.txt b/samples/client/petstore/java/default/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/default/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml deleted file mode 100644 index 0b24e120100..00000000000 --- a/samples/client/petstore/java/default/pom.xml +++ /dev/null @@ -1,181 +0,0 @@ - - 4.0.0 - io.swagger - swagger-java-client - jar - swagger-java-client - 1.0.0 - - - 2.2.0 - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.10 - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - - - - - com.sun.jersey - jersey-client - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - 2.1.5 - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 - - - - - junit - junit - ${junit-version} - test - - - - UTF-8 - 1.5.8 - 1.19.1 - 2.7.0 - 2.9.3 - 1.0.0 - 4.12 - - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java deleted file mode 100644 index 0d7898329d0..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ /dev/null @@ -1,663 +0,0 @@ -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.api.client.WebResource.Builder; - -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.MediaType; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Date; -import java.util.TimeZone; - -import java.net.URLEncoder; - -import java.io.File; -import java.io.UnsupportedEncodingException; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -import io.swagger.client.auth.Authentication; -import io.swagger.client.auth.HttpBasicAuth; -import io.swagger.client.auth.ApiKeyAuth; -import io.swagger.client.auth.OAuth; - - -public class ApiClient { - private Map defaultHeaderMap = new HashMap(); - private String basePath = "http://petstore.swagger.io/v2"; - private boolean debugging = false; - private int connectionTimeout = 0; - - private Client httpClient; - private ObjectMapper objectMapper; - - private Map authentications; - - private int statusCode; - private Map> responseHeaders; - - private DateFormat dateFormat; - - public ApiClient() { - objectMapper = new ObjectMapper(); - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - objectMapper.registerModule(new JodaModule()); - objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); - - dateFormat = ApiClient.buildDefaultDateFormat(); - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - - rebuildHttpClient(); - } - - public static DateFormat buildDefaultDateFormat() { - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - // Use UTC as the default time zone. - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; - } - - /** - * Build the Client used to make HTTP requests with the latest settings, - * i.e. objectMapper and debugging. - * TODO: better to use the Builder Pattern? - */ - public ApiClient rebuildHttpClient() { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) { - client.addFilter(new LoggingFilter()); - } - this.httpClient = client; - return this; - } - - /** - * Returns the current object mapper used for JSON serialization/deserialization. - *

    - * Note: If you make changes to the object mapper, remember to set it back via - * setObjectMapper in order to trigger HTTP client rebuilding. - *

    - */ - public ObjectMapper getObjectMapper() { - return objectMapper; - } - - public ApiClient setObjectMapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - // Need to rebuild the Client as it depends on object mapper. - rebuildHttpClient(); - return this; - } - - public Client getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(Client httpClient) { - this.httpClient = httpClient; - return this; - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Gets the status code of the previous request - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - this.debugging = debugging; - // Need to rebuild the Client as it depends on the value of debugging. - rebuildHttpClient(); - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return connectionTimeout; - } - - /** - * Set the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - httpClient.setConnectTimeout(connectionTimeout); - return this; - } - - /** - * Get the date format used to parse/format date parameters. - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Set the date format used to parse/format date parameters. - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - // Also set the date format for model (de)serialization with Date properties. - this.objectMapper.setDateFormat((DateFormat) dateFormat.clone()); - // Need to rebuild the Client as objectMapper changes. - rebuildHttpClient(); - return this; - } - - /** - * Parse the given string into Date object. - */ - public Date parseDate(String str) { - try { - return dateFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDate((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { - if(b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Serialize the given Java object into string according the given - * Content-Type (only JSON is supported for now). - */ - public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - return mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - return this.getXWWWFormUrlencodedParams(formParams); - } else { - // We let Jersey attempt to serialize the body - return obj; - } - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - private String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - if (body != null && !formParams.isEmpty()) { - throw new ApiException(500, "Cannot have body and form params"); - } - - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - Builder builder; - if (accept == null) { - builder = httpClient.resource(url).getRequestBuilder(); - } else { - builder = httpClient.resource(url).accept(accept); - } - - for (String key : headerParams.keySet()) { - builder = builder.header(key, headerParams.get(key)); - } - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - builder = builder.header(key, defaultHeaderMap.get(key)); - } - } - - ClientResponse response = null; - - if ("GET".equals(method)) { - response = (ClientResponse) builder.get(ClientResponse.class); - } else if ("POST".equals(method)) { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("PUT".equals(method)) { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("DELETE".equals(method)) { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("PATCH".equals(method)) { - response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams)); - } - else { - throw new ApiException(500, "unknown method type " + method); - } - return response; - } - - /** - * Invoke API by sending HTTP request with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - if it is not binary, otherwise null - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - - ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); - - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = response.getHeaders(); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if (returnType == null) - return null; - else - return response.getEntity(returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = response.getEntity(String.class); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Encode the given form parameters as request body. - */ - private String getXWWWFormUrlencodedParams(Map formParams) { - StringBuilder formParamBuilder = new StringBuilder(); - - for (Entry param : formParams.entrySet()) { - String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) - .append("=") - .append(URLEncoder.encode(valueStr, "utf8")); - formParamBuilder.append("&"); - } catch (UnsupportedEncodingException e) { - // move on to next - } - } - - String encodedFormParams = formParamBuilder.toString(); - if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); - } - - return encodedFormParams; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java deleted file mode 100644 index 600bb507f09..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.Map; -import java.util.List; - - -public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(String message) { - super(message); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return A map of list of string - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java deleted file mode 100644 index cbdadd6262d..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java deleted file mode 100644 index 4b44c415812..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) return; - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) return; - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; - - return true; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java deleted file mode 100644 index 03c6c81e434..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class 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/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java deleted file mode 100644 index 18ec9428c16..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ /dev/null @@ -1,131 +0,0 @@ -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import org.joda.time.LocalDate; -import org.joda.time.DateTime; -import java.math.BigDecimal; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException if fails to make API call - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); - } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (integer != null) - localVarFormParams.put("integer", integer); -if (int32 != null) - localVarFormParams.put("int32", int32); -if (int64 != null) - localVarFormParams.put("int64", int64); -if (number != null) - localVarFormParams.put("number", number); -if (_float != null) - localVarFormParams.put("float", _float); -if (_double != null) - localVarFormParams.put("double", _double); -if (string != null) - localVarFormParams.put("string", string); -if (_byte != null) - localVarFormParams.put("byte", _byte); -if (binary != null) - localVarFormParams.put("binary", binary); -if (date != null) - localVarFormParams.put("date", date); -if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); -if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java deleted file mode 100644 index 0816f9a2961..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ /dev/null @@ -1,386 +0,0 @@ -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Pet; -import java.io.File; -import io.swagger.client.model.ModelApiResponse; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void addPet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException if fails to make API call - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByTags(List tags) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException if fails to make API call - */ - public Pet getPetById(Long petId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException if fails to make API call - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (name != null) - localVarFormParams.put("name", name); -if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); -if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java deleted file mode 100644 index 4714c3ca2d3..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ /dev/null @@ -1,198 +0,0 @@ -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Order; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteOrder(String orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException if fails to make API call - */ - public Map getInventory() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(Long orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); - } - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java deleted file mode 100644 index 6369d9daa4d..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ /dev/null @@ -1,372 +0,0 @@ -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.User; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException if fails to make API call - */ - public void createUser(User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); - } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithArrayInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithListInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteUser(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException if fails to make API call - */ - public User getUserByName(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException if fails to make API call - */ - public String loginUser(String username, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs out current logged in user session - * - * @throws ApiException if fails to make API call - */ - public void logoutUser() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException if fails to make API call - */ - public void updateUser(String username, User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java deleted file mode 100644 index 6ba15566b60..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - - -public class ApiKeyAuth implements Authentication { - private final String location; - private final String paramName; - - private String apiKey; - private String apiKeyPrefix; - - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; - } - - public String getLocation() { - return location; - } - - public String getParamName() { - return paramName; - } - - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - public String getApiKeyPrefix() { - return apiKeyPrefix; - } - - public void setApiKeyPrefix(String apiKeyPrefix) { - this.apiKeyPrefix = apiKeyPrefix; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (apiKey == null) { - return; - } - String value; - if (apiKeyPrefix != null) { - value = apiKeyPrefix + " " + apiKey; - } else { - value = apiKey; - } - if (location == "query") { - queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { - headerParams.put(paramName, value); - } - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java deleted file mode 100644 index a063a6998b5..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - void applyToParams(List queryParams, Map headerParams); -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java deleted file mode 100644 index 5895370e4d4..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import com.migcomponents.migbase64.Base64; - -import java.util.Map; -import java.util.List; - -import java.io.UnsupportedEncodingException; - - -public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; - } - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java deleted file mode 100644 index 8802ebc92c8..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - - -public class OAuth implements Authentication { - private String accessToken; - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams.put("Authorization", "Bearer " + accessToken); - } - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java deleted file mode 100644 index ec1f942b0f2..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -public enum OAuthFlow { - accessCode, implicit, password, application -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java deleted file mode 100644 index ccaba7709c4..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ /dev/null @@ -1,97 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * AdditionalPropertiesClass - */ - -public class AdditionalPropertiesClass { - - private Map mapProperty = new HashMap(); - private Map> mapOfMapProperty = new HashMap>(); - - - /** - **/ - public AdditionalPropertiesClass mapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") - public Map getMapProperty() { - return mapProperty; - } - public void setMapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - } - - - /** - **/ - public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") - public Map> getMapOfMapProperty() { - return mapOfMapProperty; - } - public void setMapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); - } - - @Override - public int hashCode() { - return Objects.hash(mapProperty, mapOfMapProperty); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AdditionalPropertiesClass {\n"); - - sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); - sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java deleted file mode 100644 index 25c7d3e421c..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * Animal - */ - -public class Animal { - - private String className = null; - private String color = "red"; - - - /** - **/ - public Animal className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Animal color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - 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/default/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java deleted file mode 100644 index 647e3a893e1..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import io.swagger.client.model.Animal; -import java.util.ArrayList; -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 true; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AnimalFarm {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java deleted file mode 100644 index 99771f06952..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - - -/** - * ArrayOfArrayOfNumberOnly - */ - -public class ArrayOfArrayOfNumberOnly { - - private List> arrayArrayNumber = new ArrayList>(); - - - /** - **/ - public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("ArrayArrayNumber") - 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/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java deleted file mode 100644 index 626772b0cbb..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - - -/** - * ArrayOfNumberOnly - */ - -public class ArrayOfNumberOnly { - - private List arrayNumber = new ArrayList(); - - - /** - **/ - public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("ArrayNumber") - 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/default/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java deleted file mode 100644 index c3ffaaafe4c..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.client.model.ReadOnlyFirst; -import java.util.ArrayList; -import java.util.List; - - -/** - * ArrayTest - */ - -public class ArrayTest { - - private List arrayOfString = new ArrayList(); - private List> arrayArrayOfInteger = new ArrayList>(); - private List> arrayArrayOfModel = new ArrayList>(); - - - /** - **/ - public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") - public List getArrayOfString() { - return arrayOfString; - } - public void setArrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - } - - - /** - **/ - public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") - public List> getArrayArrayOfInteger() { - return arrayArrayOfInteger; - } - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - } - - - /** - **/ - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { - return arrayArrayOfModel; - } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && - Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); - } - - @Override - public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayTest {\n"); - - sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); - sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); - sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java deleted file mode 100644 index 5ef9e23bd96..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java +++ /dev/null @@ -1,116 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.client.model.Animal; - - -/** - * Cat - */ - -public class Cat extends Animal { - - private String className = null; - private String color = "red"; - private Boolean declawed = null; - - - /** - **/ - public Cat className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Cat color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - /** - **/ - public Cat declawed(Boolean declawed) { - this.declawed = declawed; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") - public Boolean getDeclawed() { - return declawed; - } - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Cat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java deleted file mode 100644 index c6cb703a89e..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * Category - */ - -public class Category { - - private Long id = null; - private String name = null; - - - /** - **/ - public Category id(Long id) { - this.id = id; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - public Category name(String name) { - this.name = name; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Category category = (Category) o; - return Objects.equals(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/default/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java deleted file mode 100644 index 4b3cc947cc5..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java +++ /dev/null @@ -1,116 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.client.model.Animal; - - -/** - * Dog - */ - -public class Dog extends Animal { - - private String className = null; - private String color = "red"; - private String breed = null; - - - /** - **/ - public Dog className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Dog color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - /** - **/ - public Dog breed(String breed) { - this.breed = breed; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") - 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.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Dog {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java deleted file mode 100644 index 42434e297ff..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -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; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java deleted file mode 100644 index 1c8657fd3ec..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * EnumTest - */ - -public class EnumTest { - - - /** - * Gets or Sets enumString - */ - public enum EnumStringEnum { - UPPER("UPPER"), - LOWER("lower"); - - private String value; - - EnumStringEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - } - - 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; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - } - - 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; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - } - - private EnumNumberEnum enumNumber = null; - - - /** - **/ - public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") - public EnumStringEnum getEnumString() { - return enumString; - } - public void setEnumString(EnumStringEnum enumString) { - this.enumString = enumString; - } - - - /** - **/ - public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_integer") - public EnumIntegerEnum getEnumInteger() { - return enumInteger; - } - public void setEnumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - } - - - /** - **/ - public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_number") - public EnumNumberEnum getEnumNumber() { - return enumNumber; - } - public void setEnumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - } - - - @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); - } - - @Override - public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumTest {\n"); - - sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); - sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); - sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java deleted file mode 100644 index 79376150017..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java +++ /dev/null @@ -1,327 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; - - -/** - * FormatTest - */ - -public class FormatTest { - - private Integer integer = null; - private Integer int32 = null; - private Long int64 = null; - private BigDecimal number = null; - private Float _float = null; - private Double _double = null; - private String string = null; - private byte[] _byte = null; - private byte[] binary = null; - private LocalDate date = null; - private DateTime dateTime = null; - private String uuid = null; - private String password = null; - - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ - public FormatTest integer(Integer integer) { - this.integer = integer; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") - public Integer getInteger() { - return integer; - } - public void setInteger(Integer integer) { - this.integer = integer; - } - - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ - public FormatTest int32(Integer int32) { - this.int32 = int32; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") - public Integer getInt32() { - return int32; - } - public void setInt32(Integer int32) { - this.int32 = int32; - } - - - /** - **/ - public FormatTest int64(Long int64) { - this.int64 = int64; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("int64") - public Long getInt64() { - return int64; - } - public void setInt64(Long int64) { - this.int64 = int64; - } - - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ - public FormatTest number(BigDecimal number) { - this.number = number; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") - public BigDecimal getNumber() { - return number; - } - public void setNumber(BigDecimal number) { - this.number = number; - } - - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ - public FormatTest _float(Float _float) { - this._float = _float; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") - public Float getFloat() { - return _float; - } - public void setFloat(Float _float) { - this._float = _float; - } - - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ - public FormatTest _double(Double _double) { - this._double = _double; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") - public Double getDouble() { - return _double; - } - public void setDouble(Double _double) { - this._double = _double; - } - - - /** - **/ - public FormatTest string(String string) { - this.string = string; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("string") - public String getString() { - return string; - } - public void setString(String string) { - this.string = string; - } - - - /** - **/ - public FormatTest _byte(byte[] _byte) { - this._byte = _byte; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("byte") - public byte[] getByte() { - return _byte; - } - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - - /** - **/ - public FormatTest binary(byte[] binary) { - this.binary = binary; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("binary") - public byte[] getBinary() { - return binary; - } - public void setBinary(byte[] binary) { - this.binary = binary; - } - - - /** - **/ - public FormatTest date(LocalDate date) { - this.date = date; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("date") - public LocalDate getDate() { - return date; - } - public void setDate(LocalDate date) { - this.date = date; - } - - - /** - **/ - public FormatTest dateTime(DateTime dateTime) { - this.dateTime = dateTime; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") - public DateTime getDateTime() { - return dateTime; - } - public void setDateTime(DateTime dateTime) { - this.dateTime = dateTime; - } - - - /** - **/ - public FormatTest uuid(String uuid) { - this.uuid = uuid; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - - - /** - **/ - public FormatTest password(String password) { - this.password = password; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") - 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/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java deleted file mode 100644 index 2f0972bf41e..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ /dev/null @@ -1,119 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.client.model.Animal; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.joda.time.DateTime; - - -/** - * MixedPropertiesAndAdditionalPropertiesClass - */ - -public class MixedPropertiesAndAdditionalPropertiesClass { - - private String uuid = null; - private DateTime dateTime = null; - private Map map = new HashMap(); - - - /** - **/ - public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { - this.uuid = uuid; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - - - /** - **/ - public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { - this.dateTime = dateTime; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") - public DateTime getDateTime() { - return dateTime; - } - public void setDateTime(DateTime dateTime) { - this.dateTime = dateTime; - } - - - /** - **/ - public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") - public Map getMap() { - return map; - } - public void setMap(Map map) { - this.map = map; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); - } - - @Override - public int hashCode() { - return Objects.hash(uuid, dateTime, map); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" map: ").append(toIndentedString(map)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java deleted file mode 100644 index eed3902b922..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * Model for testing model name starting with number - */ -@ApiModel(description = "Model for testing model name starting with number") - -public class Model200Response { - - private Integer name = null; - private String PropertyClass = null; - - - /** - **/ - public Model200Response name(Integer name) { - this.name = name; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") - public Integer getName() { - return name; - } - public void setName(Integer name) { - this.name = name; - } - - - /** - **/ - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("class") - 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/default/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java deleted file mode 100644 index 32fb86dd323..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * ModelApiResponse - */ - -public class ModelApiResponse { - - private Integer code = null; - private String type = null; - private String message = null; - - - /** - **/ - public ModelApiResponse code(Integer code) { - this.code = code; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("code") - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - - /** - **/ - public ModelApiResponse type(String type) { - this.type = type; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - - /** - **/ - public ModelApiResponse message(String message) { - this.message = message; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(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/default/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java deleted file mode 100644 index a076d16f964..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * Model for testing reserved words - */ -@ApiModel(description = "Model for testing reserved words") - -public class ModelReturn { - - private Integer _return = null; - - - /** - **/ - public ModelReturn _return(Integer _return) { - this._return = _return; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("return") - 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/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java deleted file mode 100644 index 1ba2cc5e4a3..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * Model for testing model name same as property name - */ -@ApiModel(description = "Model for testing model name same as property name") - -public class Name { - - private Integer name = null; - private Integer snakeCase = null; - private String property = null; - private Integer _123Number = null; - - - /** - **/ - public Name name(Integer name) { - this.name = name; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("name") - public Integer getName() { - return name; - } - public void setName(Integer name) { - this.name = name; - } - - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") - public Integer getSnakeCase() { - return snakeCase; - } - - - /** - **/ - public Name property(String property) { - this.property = property; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") - public String getProperty() { - return property; - } - public void setProperty(String property) { - this.property = property; - } - - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") - 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/default/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java deleted file mode 100644 index b3a2c788b3e..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; - - -/** - * NumberOnly - */ - -public class NumberOnly { - - private BigDecimal justNumber = null; - - - /** - **/ - public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("JustNumber") - 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/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java deleted file mode 100644 index cec651e73a6..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ /dev/null @@ -1,199 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.joda.time.DateTime; - - -/** - * Order - */ - -public class Order { - - private Long id = null; - private Long petId = null; - private Integer quantity = null; - private DateTime shipDate = null; - - /** - * Order Status - */ - public enum StatusEnum { - PLACED("placed"), - APPROVED("approved"), - DELIVERED("delivered"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - } - - private StatusEnum status = null; - private Boolean complete = false; - - - /** - **/ - public Order id(Long id) { - this.id = id; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - public Order petId(Long petId) { - this.petId = petId; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - - /** - **/ - public Order quantity(Integer quantity) { - this.quantity = quantity; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - - /** - **/ - public Order shipDate(DateTime shipDate) { - this.shipDate = shipDate; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") - public DateTime getShipDate() { - return shipDate; - } - public void setShipDate(DateTime shipDate) { - this.shipDate = shipDate; - } - - - /** - * Order Status - **/ - public Order status(StatusEnum status) { - this.status = status; - return this; - } - - @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - - /** - **/ - public Order complete(Boolean complete) { - this.complete = complete; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Order order = (Order) o; - return Objects.equals(this.id, order.id) && - Objects.equals(this.petId, order.petId) && - Objects.equals(this.quantity, order.quantity) && - Objects.equals(this.shipDate, order.shipDate) && - Objects.equals(this.status, order.status) && - Objects.equals(this.complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java deleted file mode 100644 index da8b76ad024..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ /dev/null @@ -1,202 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; -import java.util.ArrayList; -import java.util.List; - - -/** - * Pet - */ - -public class Pet { - - private Long id = null; - private Category category = null; - private String name = null; - private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); - - /** - * pet status in the store - */ - public enum StatusEnum { - AVAILABLE("available"), - PENDING("pending"), - SOLD("sold"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - } - - private StatusEnum status = null; - - - /** - **/ - public Pet id(Long id) { - this.id = id; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - public Pet category(Category category) { - this.category = category; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") - public Category getCategory() { - return category; - } - public void setCategory(Category category) { - this.category = category; - } - - - /** - **/ - public Pet name(String name) { - this.name = name; - return this; - } - - @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - /** - **/ - public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") - public List getPhotoUrls() { - return photoUrls; - } - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - - /** - **/ - public Pet tags(List tags) { - this.tags = tags; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - - - /** - * pet status in the store - **/ - public Pet status(StatusEnum status) { - this.status = status; - return this; - } - - @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - - @Override - public boolean equals(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/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java deleted file mode 100644 index fdc3587df0e..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ /dev/null @@ -1,84 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * ReadOnlyFirst - */ - -public class ReadOnlyFirst { - - private String bar = null; - private String baz = null; - - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") - public String getBar() { - return bar; - } - - - /** - **/ - public ReadOnlyFirst baz(String baz) { - this.baz = baz; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") - public String getBaz() { - return baz; - } - public void setBaz(String baz) { - this.baz = baz; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(this.bar, readOnlyFirst.bar) && - Objects.equals(this.baz, readOnlyFirst.baz); - } - - @Override - public int hashCode() { - return Objects.hash(bar, baz); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ReadOnlyFirst {\n"); - - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java deleted file mode 100644 index 24e57756cb2..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java +++ /dev/null @@ -1,74 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * SpecialModelName - */ - -public class SpecialModelName { - - private Long specialPropertyName = null; - - - /** - **/ - public SpecialModelName specialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("$special[property.name]") - 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/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java deleted file mode 100644 index 9d3bdd8cb9e..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * Tag - */ - -public class Tag { - - private Long id = null; - private String name = null; - - - /** - **/ - public Tag id(Long id) { - this.id = id; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - public Tag name(String name) { - this.name = name; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Tag tag = (Tag) o; - return Objects.equals(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/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java deleted file mode 100644 index f23553660de..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ /dev/null @@ -1,215 +0,0 @@ -package io.swagger.client.model; - -import com.fasterxml.jackson.annotation.JsonValue; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - - -/** - * User - */ - -public class User { - - private Long id = null; - private String username = null; - private String firstName = null; - private String lastName = null; - private String email = null; - private String password = null; - private String phone = null; - private Integer userStatus = null; - - - /** - **/ - public User id(Long id) { - this.id = id; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - public User username(String username) { - this.username = username; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - - /** - **/ - public User firstName(String firstName) { - this.firstName = firstName; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - - /** - **/ - public User lastName(String lastName) { - this.lastName = lastName; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - - /** - **/ - public User email(String email) { - this.email = email; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - - /** - **/ - public User password(String password) { - this.password = password; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - - /** - **/ - public User phone(String phone) { - this.phone = phone; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - - /** - * User Status - **/ - public User userStatus(Integer userStatus) { - this.userStatus = userStatus; - return this; - } - - @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - User user = (User) o; - return Objects.equals(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/default/.travis.yml b/samples/client/petstore/java/feign/.travis.yml similarity index 100% rename from samples/client/petstore/java/default/.travis.yml rename to samples/client/petstore/java/feign/.travis.yml diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle index 5b79cf3c5a5..50c4634a73f 100644 --- a/samples/client/petstore/java/feign/build.gradle +++ b/samples/client/petstore/java/feign/build.gradle @@ -94,9 +94,9 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.8" + swagger_annotations_version = "1.5.9" jackson_version = "2.7.5" - feign_version = "8.16.0" + feign_version = "8.17.0" junit_version = "4.12" oltu_version = "1.0.1" } diff --git a/samples/client/petstore/java/feign/build.sbt b/samples/client/petstore/java/feign/build.sbt index 4e0905c8820..10b1f875927 100644 --- a/samples/client/petstore/java/feign/build.sbt +++ b/samples/client/petstore/java/feign/build.sbt @@ -9,9 +9,9 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.9" % "compile", "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", - "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile", diff --git a/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/feign/docs/AdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md rename to samples/client/petstore/java/feign/docs/AdditionalPropertiesClass.md diff --git a/samples/client/petstore/java/default/docs/Animal.md b/samples/client/petstore/java/feign/docs/Animal.md similarity index 100% rename from samples/client/petstore/java/default/docs/Animal.md rename to samples/client/petstore/java/feign/docs/Animal.md diff --git a/samples/client/petstore/java/default/docs/AnimalFarm.md b/samples/client/petstore/java/feign/docs/AnimalFarm.md similarity index 100% rename from samples/client/petstore/java/default/docs/AnimalFarm.md rename to samples/client/petstore/java/feign/docs/AnimalFarm.md diff --git a/samples/client/petstore/java/default/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/feign/docs/ArrayOfArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayOfArrayOfNumberOnly.md rename to samples/client/petstore/java/feign/docs/ArrayOfArrayOfNumberOnly.md diff --git a/samples/client/petstore/java/default/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/feign/docs/ArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayOfNumberOnly.md rename to samples/client/petstore/java/feign/docs/ArrayOfNumberOnly.md diff --git a/samples/client/petstore/java/default/docs/ArrayTest.md b/samples/client/petstore/java/feign/docs/ArrayTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayTest.md rename to samples/client/petstore/java/feign/docs/ArrayTest.md diff --git a/samples/client/petstore/java/default/docs/Cat.md b/samples/client/petstore/java/feign/docs/Cat.md similarity index 100% rename from samples/client/petstore/java/default/docs/Cat.md rename to samples/client/petstore/java/feign/docs/Cat.md diff --git a/samples/client/petstore/java/default/docs/Category.md b/samples/client/petstore/java/feign/docs/Category.md similarity index 100% rename from samples/client/petstore/java/default/docs/Category.md rename to samples/client/petstore/java/feign/docs/Category.md diff --git a/samples/client/petstore/java/default/docs/Dog.md b/samples/client/petstore/java/feign/docs/Dog.md similarity index 100% rename from samples/client/petstore/java/default/docs/Dog.md rename to samples/client/petstore/java/feign/docs/Dog.md diff --git a/samples/client/petstore/java/default/docs/EnumClass.md b/samples/client/petstore/java/feign/docs/EnumClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/EnumClass.md rename to samples/client/petstore/java/feign/docs/EnumClass.md diff --git a/samples/client/petstore/java/default/docs/EnumTest.md b/samples/client/petstore/java/feign/docs/EnumTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/EnumTest.md rename to samples/client/petstore/java/feign/docs/EnumTest.md diff --git a/samples/client/petstore/java/feign/docs/FakeApi.md b/samples/client/petstore/java/feign/docs/FakeApi.md new file mode 100644 index 00000000000..21a4db7c377 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/FakeApi.md @@ -0,0 +1,122 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/default/docs/FormatTest.md b/samples/client/petstore/java/feign/docs/FormatTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/FormatTest.md rename to samples/client/petstore/java/feign/docs/FormatTest.md diff --git a/samples/client/petstore/java/feign/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/feign/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/feign/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/feign/docs/MapTest.md b/samples/client/petstore/java/feign/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/feign/docs/MapTest.md @@ -0,0 +1,17 @@ + +# 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 +---- | ----- + + + diff --git a/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/feign/docs/MixedPropertiesAndAdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md rename to samples/client/petstore/java/feign/docs/MixedPropertiesAndAdditionalPropertiesClass.md diff --git a/samples/client/petstore/java/default/docs/Model200Response.md b/samples/client/petstore/java/feign/docs/Model200Response.md similarity index 100% rename from samples/client/petstore/java/default/docs/Model200Response.md rename to samples/client/petstore/java/feign/docs/Model200Response.md diff --git a/samples/client/petstore/java/default/docs/ModelApiResponse.md b/samples/client/petstore/java/feign/docs/ModelApiResponse.md similarity index 100% rename from samples/client/petstore/java/default/docs/ModelApiResponse.md rename to samples/client/petstore/java/feign/docs/ModelApiResponse.md diff --git a/samples/client/petstore/java/default/docs/ModelReturn.md b/samples/client/petstore/java/feign/docs/ModelReturn.md similarity index 100% rename from samples/client/petstore/java/default/docs/ModelReturn.md rename to samples/client/petstore/java/feign/docs/ModelReturn.md diff --git a/samples/client/petstore/java/default/docs/Name.md b/samples/client/petstore/java/feign/docs/Name.md similarity index 100% rename from samples/client/petstore/java/default/docs/Name.md rename to samples/client/petstore/java/feign/docs/Name.md diff --git a/samples/client/petstore/java/default/docs/NumberOnly.md b/samples/client/petstore/java/feign/docs/NumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/NumberOnly.md rename to samples/client/petstore/java/feign/docs/NumberOnly.md diff --git a/samples/client/petstore/java/default/docs/Order.md b/samples/client/petstore/java/feign/docs/Order.md similarity index 100% rename from samples/client/petstore/java/default/docs/Order.md rename to samples/client/petstore/java/feign/docs/Order.md diff --git a/samples/client/petstore/java/default/docs/Pet.md b/samples/client/petstore/java/feign/docs/Pet.md similarity index 100% rename from samples/client/petstore/java/default/docs/Pet.md rename to samples/client/petstore/java/feign/docs/Pet.md diff --git a/samples/client/petstore/java/default/docs/PetApi.md b/samples/client/petstore/java/feign/docs/PetApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/PetApi.md rename to samples/client/petstore/java/feign/docs/PetApi.md diff --git a/samples/client/petstore/java/default/docs/ReadOnlyFirst.md b/samples/client/petstore/java/feign/docs/ReadOnlyFirst.md similarity index 100% rename from samples/client/petstore/java/default/docs/ReadOnlyFirst.md rename to samples/client/petstore/java/feign/docs/ReadOnlyFirst.md diff --git a/samples/client/petstore/java/default/docs/SpecialModelName.md b/samples/client/petstore/java/feign/docs/SpecialModelName.md similarity index 100% rename from samples/client/petstore/java/default/docs/SpecialModelName.md rename to samples/client/petstore/java/feign/docs/SpecialModelName.md diff --git a/samples/client/petstore/java/default/docs/StoreApi.md b/samples/client/petstore/java/feign/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/StoreApi.md rename to samples/client/petstore/java/feign/docs/StoreApi.md diff --git a/samples/client/petstore/java/default/docs/Tag.md b/samples/client/petstore/java/feign/docs/Tag.md similarity index 100% rename from samples/client/petstore/java/default/docs/Tag.md rename to samples/client/petstore/java/feign/docs/Tag.md diff --git a/samples/client/petstore/java/default/docs/User.md b/samples/client/petstore/java/feign/docs/User.md similarity index 100% rename from samples/client/petstore/java/default/docs/User.md rename to samples/client/petstore/java/feign/docs/User.md diff --git a/samples/client/petstore/java/default/docs/UserApi.md b/samples/client/petstore/java/feign/docs/UserApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/UserApi.md rename to samples/client/petstore/java/feign/docs/UserApi.md diff --git a/samples/client/petstore/java/feign/gradlew b/samples/client/petstore/java/feign/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/feign/gradlew.bat b/samples/client/petstore/java/feign/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/feign/gradlew.bat +++ b/samples/client/petstore/java/feign/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/feign/hello.txt b/samples/client/petstore/java/feign/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/feign/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 84cc6f1ddc5..72f588a896a 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -95,6 +95,11 @@
    + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 +
    @@ -160,8 +165,8 @@ 1.7 ${java.version} ${java.version} - 1.5.8 - 8.16.0 + 1.5.9 + 8.17.0 2.7.5 4.12 1.0.0 diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index 75b3a96f2c7..d4844ec8d05 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -41,10 +41,12 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { RequestInterceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -130,6 +132,7 @@ private ObjectMapper createObjectMapper() { objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.setDateFormat(new RFC3339DateFormat()); objectMapper.registerModule(new JodaModule()); return objectMapper; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 179a2834da9..85e7fad4d72 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -8,7 +8,6 @@ import java.util.*; import java.text.DateFormat; -import java.text.SimpleDateFormat; import feign.codec.EncodeException; import feign.codec.Encoder; @@ -32,12 +31,8 @@ public class FormAwareEncoder implements Encoder { public FormAwareEncoder(Encoder delegate) { this.delegate = delegate; - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + this.dateFormat = new RFC3339DateFormat();; - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); this.boundaryBytes = BOUNDARY.getBytes(UTF_8); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..3d287008be5 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.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/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..31140c76df4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/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 dbabdc64995..b843c876ebb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -2,6 +2,7 @@ import io.swagger.client.ApiClient; +import io.swagger.client.model.Client; import org.joda.time.LocalDate; import java.math.BigDecimal; import org.joda.time.DateTime; @@ -16,17 +17,31 @@ public interface FakeApi extends ApiClient.Api { + /** + * To test \"client\" model + * + * @param body client model (required) + * @return Client + */ + @RequestLine("PATCH /fake") + @Headers({ + "Content-type: application/json", + "Accept: application/json", + }) + Client testClientModel(Client body); + /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -38,5 +53,28 @@ public interface FakeApi extends ApiClient.Api { "Content-type: application/xml; charset=utf-8", "Accept: application/xml; charset=utf-8,application/json; charset=utf-8", }) - void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); + void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("patternWithoutDelimiter") String patternWithoutDelimiter, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("string") String string, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); + + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return void + */ + @RequestLine("GET /fake?enum_query_string_array={enumQueryStringArray}&enum_query_string={enumQueryString}&enum_query_integer={enumQueryInteger}") + @Headers({ + "Content-type: application/json", + "Accept: application/json", + "enum_header_string_array: {enumHeaderStringArray}", + + "enum_header_string: {enumHeaderString}" + }) + void testEnumParameters(@Param("enumFormStringArray") List enumFormStringArray, @Param("enumFormString") String enumFormString, @Param("enumHeaderStringArray") List enumHeaderStringArray, @Param("enumHeaderString") String enumHeaderString, @Param("enumQueryStringArray") List enumQueryStringArray, @Param("enumQueryString") String enumQueryString, @Param("enumQueryInteger") BigDecimal enumQueryInteger, @Param("enumQueryDouble") Double enumQueryDouble); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index e486495c5a9..b6fbdf208dc 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -40,7 +40,7 @@ public interface PetApi extends ApiClient.Api { @Headers({ "Content-type: application/json", "Accept: application/json", - "apiKey: {apiKey}" + "api_key: {apiKey}" }) void deletePet(@Param("petId") Long petId, @Param("apiKey") String apiKey); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 067672104a9..6e963f39d5c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -32,10 +32,10 @@ public void setApiKey(String apiKey) { @Override public void apply(RequestTemplate template) { - if (location == "query") { + if ("query".equals(location)) { template.query(paramName, apiKey); - } else if (location == "header") { + } else if ("header".equals(location)) { template.header(paramName, apiKey); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..18c25738e0f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ccaba7709c4..2da13804a0d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -15,40 +40,54 @@ */ public class AdditionalPropertiesClass { - + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; } - + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - - /** - **/ public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; return this; } - + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 25c7d3e421c..346da224ad1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +37,44 @@ */ 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(example = "null", required = true, value = "") - @JsonProperty("className") 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(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index 647e3a893e1..563476ccb3d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,6 +1,30 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -12,9 +36,7 @@ */ public class AnimalFarm extends ArrayList { - - @Override public boolean equals(java.lang.Object o) { if (this == o) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..a99f2009385 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", 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/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..1aaf27b9921 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", 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/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 6c1eb23d8d0..124d8bfa3a1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,10 +1,36 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; @@ -14,58 +40,80 @@ */ public class ArrayTest { - + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } - + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - - /** - **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } - + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - - /** - **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 5ef9e23bd96..41dc312a10f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +38,23 @@ */ public class Cat extends Animal { - - private String className = null; - private String color = "red"; + @JsonProperty("declawed") private Boolean declawed = null; - - /** - **/ - public Cat className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Cat color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - /** - **/ public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; } - + + /** + * Get declawed + * @return declawed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } @@ -79,15 +69,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -95,8 +83,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index c6cb703a89e..ba4ce89c297 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +37,44 @@ */ 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(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Category name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..43ade4b6fcb --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 4b3cc947cc5..788aee5c226 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +38,23 @@ */ public class Dog extends Animal { - - private String className = null; - private String color = "red"; + @JsonProperty("breed") private String breed = null; - - /** - **/ - public Dog className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Dog color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - /** - **/ public Dog breed(String breed) { this.breed = breed; return this; } - + + /** + * Get breed + * @return breed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } @@ -79,15 +69,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -95,8 +83,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..45295c524f6 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,190 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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; + } + + @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; + } + + @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 = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index 42434e297ff..f9887c69340 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,16 +1,44 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; + /** * Gets or Sets EnumClass */ public enum EnumClass { + _ABC("_abc"), + _EFG("-efg"), + _XYZ_("(xyz)"); private String value; @@ -20,9 +48,18 @@ public enum EnumClass { } @Override - @JsonValue 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/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 1c8657fd3ec..a7268316c40 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,9 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,13 +37,12 @@ */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { UPPER("UPPER"), + LOWER("lower"); private String value; @@ -29,12 +52,22 @@ public enum EnumStringEnum { } @Override - @JsonValue 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; /** @@ -42,6 +75,7 @@ public String toString() { */ public enum EnumIntegerEnum { NUMBER_1(1), + NUMBER_MINUS_1(-1); private Integer value; @@ -51,12 +85,22 @@ public enum EnumIntegerEnum { } @Override - @JsonValue 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; /** @@ -64,6 +108,7 @@ public String toString() { */ public enum EnumNumberEnum { NUMBER_1_DOT_1(1.1), + NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -73,61 +118,74 @@ public enum EnumNumberEnum { } @Override - @JsonValue 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; - - /** - **/ public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; } - + + /** + * Get enumString + * @return enumString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") 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(example = "null", value = "") - @JsonProperty("enum_integer") 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(example = "null", value = "") - @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 79376150017..2b5b4204281 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -15,248 +40,285 @@ */ 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 DateTime dateTime = null; + + @JsonProperty("uuid") private String uuid = null; + + @JsonProperty("password") private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } - + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } - + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") 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(example = "null", value = "") - @JsonProperty("int64") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } - + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ public FormatTest _float(Float _float) { this._float = _float; return this; } - + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ public FormatTest _double(Double _double) { this._double = _double; return this; } - + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") 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(example = "null", value = "") - @JsonProperty("string") 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(example = "null", required = true, value = "") - @JsonProperty("byte") 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(example = "null", value = "") - @JsonProperty("binary") 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(example = "null", required = true, value = "") - @JsonProperty("date") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - - /** - **/ public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public FormatTest uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public FormatTest password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d874a545244 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,105 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", 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/feign/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..f8cf1ad5d1a --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", 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/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2f0972bf41e..20958fd50d8 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -17,58 +42,70 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - + @JsonProperty("uuid") private String uuid = null; + + @JsonProperty("dateTime") private DateTime dateTime = null; + + @JsonProperty("map") private Map map = new HashMap(); - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; return this; } - + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index eed3902b922..8f48dd8020e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,42 +38,46 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - + @JsonProperty("name") private Integer name = null; - private String PropertyClass = null; - - /** - **/ + @JsonProperty("class") + private String propertyClass = null; + public Model200Response name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - - /** - **/ - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } - + + /** + * Get propertyClass + * @return propertyClass + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("class") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -62,12 +91,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -76,7 +105,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index 32fb86dd323..70ee2a834c0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,58 +37,65 @@ */ 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(example = "null", value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + + /** + * Get type + * @return type + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + + /** + * Get message + * @return message + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index a076d16f964..28294a15090 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,22 +38,23 @@ @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(example = "null", value = "") - @JsonProperty("return") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 1ba2cc5e4a3..4b70e8df1a6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,56 +38,68 @@ @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(example = "null", required = true, value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - + /** + * Get snakeCase + * @return snakeCase + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - - /** - **/ public Name property(String property) { this.property = property; return this; } - + + /** + * Get property + * @return property + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - + /** + * Get _123Number + * @return _123Number + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..ad74058d2e5 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index cec651e73a6..1616b030b9d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -14,10 +38,16 @@ */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; + + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -25,7 +55,9 @@ public class Order { */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -35,114 +67,131 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + + @JsonProperty("complete") private Boolean complete = false; - - /** - **/ public Order id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + + /** + * Get petId + * @return petId + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + + /** + * Order Status + * @return status + **/ @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + + /** + * Get complete + * @return complete + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index da8b76ad024..a89e0ea3e05 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -1,9 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -17,11 +41,19 @@ */ 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 = new ArrayList(); /** @@ -29,7 +61,9 @@ public class Pet { */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -39,113 +73,138 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; - - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + + /** + * Get category + * @return category + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - - /** - **/ public Pet name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index fdc3587df0e..63e11bf14fd 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,30 +37,35 @@ */ public class ReadOnlyFirst { - + @JsonProperty("bar") private String bar = null; + + @JsonProperty("baz") private String baz = null; - + /** + * Get bar + * @return bar + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") public String getBar() { return bar; } - - /** - **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; } - + + /** + * Get baz + * @return baz + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index 24e57756cb2..f8c5c06ca40 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,22 +37,23 @@ */ 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(example = "null", value = "") - @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index 9d3bdd8cb9e..27be94678da 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +37,44 @@ */ 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(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Tag name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index f23553660de..84e3b147049 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,149 +37,170 @@ */ 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(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public User username(String username) { this.username = username; return this; } - + + /** + * Get username + * @return username + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - - /** - **/ public User email(String email) { this.email = email; return this; } - + + /** + * Get email + * @return email + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - - /** - **/ public User password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + + /** + * Get phone + * @return phone + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/default/.gitignore b/samples/client/petstore/java/jersey1/.gitignore similarity index 100% rename from samples/client/petstore/java/default/.gitignore rename to samples/client/petstore/java/jersey1/.gitignore diff --git a/samples/client/petstore/java/jersey1/.swagger-codegen-ignore b/samples/client/petstore/java/jersey1/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/jersey1/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# 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/jersey1/.travis.yml b/samples/client/petstore/java/jersey1/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/jersey1/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: 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/jersey1/LICENSE b/samples/client/petstore/java/jersey1/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/jersey1/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/jersey1/README.md b/samples/client/petstore/java/jersey1/README.md new file mode 100644 index 00000000000..c824c828980 --- /dev/null +++ b/samples/client/petstore/java/jersey1/README.md @@ -0,0 +1,183 @@ +# swagger-java-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-java-client + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-java-client:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-java-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.FakeApi; + +import java.io.File; +import java.util.*; + +public class FakeApiExample { + + public static void main(String[] args) { + + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + DateTime dateTime = new DateTime(); // DateTime | None + String password = "password_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Cat](docs/Cat.md) + - [Category](docs/Category.md) + - [Dog](docs/Dog.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [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) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin 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 issue. + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/java/jersey1/build.gradle b/samples/client/petstore/java/jersey1/build.gradle new file mode 100644 index 00000000000..1e4969e26fd --- /dev/null +++ b/samples/client/petstore/java/jersey1/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 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-java-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.8" + jackson_version = "2.7.5" + jersey_version = "1.19.1" + jodatime_version = "2.9.4" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + compile "joda-time:joda-time:$jodatime_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/jersey1/build.sbt b/samples/client/petstore/java/jersey1/build.sbt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/java/jersey1/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/jersey1/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/Animal.md b/samples/client/petstore/java/jersey1/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/AnimalFarm.md b/samples/client/petstore/java/jersey1/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/jersey1/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey1/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey1/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/ArrayTest.md b/samples/client/petstore/java/jersey1/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/Cat.md b/samples/client/petstore/java/jersey1/docs/Cat.md new file mode 100644 index 00000000000..6e9f71ce7dd --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/Cat.md @@ -0,0 +1,10 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/docs/Category.md b/samples/client/petstore/java/jersey1/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/Client.md b/samples/client/petstore/java/jersey1/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/docs/Dog.md b/samples/client/petstore/java/jersey1/docs/Dog.md new file mode 100644 index 00000000000..ac7cea323ff --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/Dog.md @@ -0,0 +1,10 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/docs/EnumArrays.md b/samples/client/petstore/java/jersey1/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/EnumClass.md b/samples/client/petstore/java/jersey1/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/EnumTest.md b/samples/client/petstore/java/jersey1/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/jersey1/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md new file mode 100644 index 00000000000..29813bd9349 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/FakeApi.md @@ -0,0 +1,189 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +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 + + + +# **testClientModel** +> Client testClientModel(body) + +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 = B; // 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 +DateTime dateTime = new DateTime(); // DateTime | 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** | **DateTime**| 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 + +### 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) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | 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** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/jersey1/docs/FormatTest.md b/samples/client/petstore/java/jersey1/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/jersey1/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey1/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/MapTest.md b/samples/client/petstore/java/jersey1/docs/MapTest.md new file mode 100644 index 00000000000..714a97a40d9 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/docs/Model200Response.md b/samples/client/petstore/java/jersey1/docs/Model200Response.md new file mode 100644 index 00000000000..5b3a9a0e46d --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/ModelApiResponse.md b/samples/client/petstore/java/jersey1/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/ModelReturn.md b/samples/client/petstore/java/jersey1/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/docs/Name.md b/samples/client/petstore/java/jersey1/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/NumberOnly.md b/samples/client/petstore/java/jersey1/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/Order.md b/samples/client/petstore/java/jersey1/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/jersey1/docs/Pet.md b/samples/client/petstore/java/jersey1/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/PetApi.md b/samples/client/petstore/java/jersey1/docs/PetApi.md new file mode 100644 index 00000000000..3b5f84043e3 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> 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/jersey1/docs/ReadOnlyFirst.md b/samples/client/petstore/java/jersey1/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/SpecialModelName.md b/samples/client/petstore/java/jersey1/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/docs/StoreApi.md b/samples/client/petstore/java/jersey1/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> 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>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/jersey1/docs/Tag.md b/samples/client/petstore/java/jersey1/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/User.md b/samples/client/petstore/java/jersey1/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/docs/UserApi.md b/samples/client/petstore/java/jersey1/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> 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/jersey1/git_push.sh b/samples/client/petstore/java/jersey1/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/gradle.properties b/samples/client/petstore/java/jersey1/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/gradlew b/samples/client/petstore/java/jersey1/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/gradlew.bat b/samples/client/petstore/java/jersey1/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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/jersey1/pom.xml b/samples/client/petstore/java/jersey1/pom.xml new file mode 100644 index 00000000000..e40088ac44c --- /dev/null +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -0,0 +1,186 @@ + + 4.0.0 + io.swagger + swagger-java-client + jar + swagger-java-client + 1.0.0 + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + joda-time + joda-time + ${jodatime-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.8 + 1.19.1 + 2.7.5 + 2.9.4 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/default/settings.gradle b/samples/client/petstore/java/jersey1/settings.gradle similarity index 100% rename from samples/client/petstore/java/default/settings.gradle rename to samples/client/petstore/java/jersey1/settings.gradle diff --git a/samples/client/petstore/java/default/src/main/AndroidManifest.xml b/samples/client/petstore/java/jersey1/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/java/default/src/main/AndroidManifest.xml rename to samples/client/petstore/java/jersey1/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..040449d3e4b --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,689 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.GenericType; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.LoggingFilter; +import com.sun.jersey.api.client.WebResource.Builder; + +import com.sun.jersey.multipart.FormDataMultiPart; +import com.sun.jersey.multipart.file.FileDataBodyPart; + +import javax.ws.rs.core.Response.Status.Family; +import javax.ws.rs.core.MediaType; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + + +public class ApiClient { + private Map defaultHeaderMap = new HashMap(); + private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private ObjectMapper objectMapper; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + objectMapper.registerModule(new JodaModule()); + objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); + + dateFormat = ApiClient.buildDefaultDateFormat(); + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + rebuildHttpClient(); + } + + public static DateFormat buildDefaultDateFormat() { + return new RFC3339DateFormat(); + } + + /** + * Build the Client used to make HTTP requests with the latest settings, + * i.e. objectMapper and debugging. + * TODO: better to use the Builder Pattern? + */ + public ApiClient rebuildHttpClient() { + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); + if (debugging) { + client.addFilter(new LoggingFilter()); + } + this.httpClient = client; + return this; + } + + /** + * Returns the current object mapper used for JSON serialization/deserialization. + *

    + * Note: If you make changes to the object mapper, remember to set it back via + * setObjectMapper in order to trigger HTTP client rebuilding. + *

    + */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + public ApiClient setObjectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + // Need to rebuild the Client as it depends on object mapper. + rebuildHttpClient(); + return this; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Need to rebuild the Client as it depends on the value of debugging. + rebuildHttpClient(); + return this; + } + + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.setConnectTimeout(connectionTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // Also set the date format for model (de)serialization with Date properties. + this.objectMapper.setDateFormat((DateFormat) dateFormat.clone()); + // Need to rebuild the Client as objectMapper changes. + rebuildHttpClient(); + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). + */ + public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if( param.getValue() instanceof List && !( ( List ) param.getValue() ).isEmpty() + && ( ( List ) param.getValue() ).get( 0 ) instanceof File ) { + @SuppressWarnings( "unchecked" ) + List files = ( List ) param.getValue(); + for( File file : files ) { + mp.bodyPart( new FileDataBodyPart( param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE ) ); + } + } else if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + return mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + return this.getXWWWFormUrlencodedParams(formParams); + } else { + // We let Jersey attempt to serialize the body + return obj; + } + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + private String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + if (body != null && !formParams.isEmpty()) { + throw new ApiException(500, "Cannot have body and form params"); + } + + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + Builder builder; + if (accept == null) { + builder = httpClient.resource(url).getRequestBuilder(); + } else { + builder = httpClient.resource(url).accept(accept); + } + + for (String key : headerParams.keySet()) { + builder = builder.header(key, headerParams.get(key)); + } + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + builder = builder.header(key, defaultHeaderMap.get(key)); + } + } + + ClientResponse response = null; + + if ("GET".equals(method)) { + response = (ClientResponse) builder.get(ClientResponse.class); + } else if ("POST".equals(method)) { + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); + } else if ("PUT".equals(method)) { + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); + } else if ("DELETE".equals(method)) { + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); + } else if ("PATCH".equals(method)) { + response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams)); + } + else { + throw new ApiException(500, "unknown method type " + method); + } + return response; + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object - if it is not binary, otherwise null + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { + + ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = response.getHeaders(); + + if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (returnType == null) + return null; + else + return response.getEntity(returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = response.getEntity(String.class); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Encode the given form parameters as request body. + */ + private String getXWWWFormUrlencodedParams(Map formParams) { + StringBuilder formParamBuilder = new StringBuilder(); + + for (Entry param : formParams.entrySet()) { + String valueStr = parameterToString(param.getValue()); + try { + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) + .append("=") + .append(URLEncoder.encode(valueStr, "utf8")); + formParamBuilder.append("&"); + } catch (UnsupportedEncodingException e) { + // move on to next + } + } + + String encodedFormParams = formParamBuilder.toString(); + if (encodedFormParams.endsWith("&")) { + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); + } + + return encodedFormParams; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..02a967d8373 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..57e53b2d598 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..9ad2d246519 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..d662f9457d7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,44 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.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/jersey1/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..31140c76df4 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,67 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class 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/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 new file mode 100644 index 00000000000..bfa6f66e56d --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,258 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api; + +import com.sun.jersey.api.client.GenericType; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.model.*; +import io.swagger.client.Pair; + +import io.swagger.client.model.Client; +import org.joda.time.LocalDate; +import java.math.BigDecimal; +import org.joda.time.DateTime; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * To test \"client\" model + * + * @param body client model (required) + * @return Client + * @throws ApiException if fails to make API call + */ + public Client testClientModel(Client body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling testClientModel"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @throws ApiException if fails to make API call + */ + 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, DateTime dateTime, String password, String paramCallback) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); +if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); +if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); +if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} 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 new file mode 100644 index 00000000000..90c256ee9ce --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,410 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api; + +import com.sun.jersey.api.client.GenericType; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.model.*; +import io.swagger.client.Pair; + +import io.swagger.client.model.Pet; +import io.swagger.client.model.ModelApiResponse; +import java.io.File; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void addPet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException if fails to make API call + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet getPetById(Long petId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException if fails to make API call + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (name != null) + localVarFormParams.put("name", name); +if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException if fails to make API call + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); +if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..99b240aa071 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,222 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api; + +import com.sun.jersey.api.client.GenericType; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.model.*; +import io.swagger.client.Pair; + +import io.swagger.client.model.Order; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteOrder(String orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + * @throws ApiException if fails to make API call + */ + public Map getInventory() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order getOrderById(Long orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..9325af8abda --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,396 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api; + +import com.sun.jersey.api.client.GenericType; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.model.*; +import io.swagger.client.Pair; + +import io.swagger.client.model.User; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException if fails to make API call + */ + public void createUser(User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithListInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteUser(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException if fails to make API call + */ + public User getUserByName(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException if fails to make API call + */ + public String loginUser(String username, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs out current logged in user session + * + * @throws ApiException if fails to make API call + */ + public void logoutUser() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException if fails to make API call + */ + public void updateUser(String username, User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..0e0fdb63fb3 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,87 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..0ff06e3b86f --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..420178c112d --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,70 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import com.migcomponents.migbase64.Base64; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..c1b64913ab8 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..18c25738e0f --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..db74fca66a7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..6799afd7beb --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,123 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +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(example = "null", 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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..8a50c9c6cb5 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,76 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..e57ce230767 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..6dafaf06c62 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..8bb3d0c57b7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..949df449199 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -0,0 +1,102 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..b8e278b2a74 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,123 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..024f8cb3b72 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..00e981ab434 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -0,0 +1,102 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..14047380180 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,190 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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; + } + + @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; + } + + @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 = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..c2f4ae53735 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java @@ -0,0 +1,64 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = 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/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..53665518adb --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,236 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = 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; + } + + @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; + } + + @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; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..b7f9513f03c --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,389 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +/** + * 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 DateTime dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(example = "null", 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.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..1cd90edaae8 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,105 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..60751c48d8c --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..b738c397191 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..849f208ff7a --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..79d704bc1bf --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,146 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..0d85efb9884 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..cc3e7252197 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,152 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..c7eb42d616c --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..6dd1a55c543 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,248 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; + +/** + * 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 DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = 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(example = "null", 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(example = "null", 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(example = "null", value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(example = "null", 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(example = "null", value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..06e43f726f3 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,261 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = 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(example = "null", 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(example = "null", 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(example = "null", 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) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..5c7ed3ec0a6 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,114 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..74695119c3e --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..a886efeac4b --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,123 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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/jersey1/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..f73fff70097 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,261 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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/default/src/test/java/io/swagger/PetstoreProfiling.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/PetstoreProfiling.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/PetstoreProfiling.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/TestUtils.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/TestUtils.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java similarity index 100% rename from samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 00000000000..867c454bff6 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,62 @@ +package io.swagger.client.model; + +import java.io.StringWriter; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.SerializationFeature.*; + +public class EnumValueTest { + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\"}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + + } + +} diff --git a/samples/client/petstore/java/jersey2-java8/.gitignore b/samples/client/petstore/java/jersey2-java8/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/.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/jersey2-java8/.swagger-codegen-ignore b/samples/client/petstore/java/jersey2-java8/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/.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/jersey2-java8/.travis.yml b/samples/client/petstore/java/jersey2-java8/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: 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/jersey2-java8/LICENSE b/samples/client/petstore/java/jersey2-java8/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/jersey2-java8/README.md b/samples/client/petstore/java/jersey2-java8/README.md new file mode 100644 index 00000000000..579d98c8224 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/README.md @@ -0,0 +1,177 @@ +# swagger-petstore-jersey2 + +## 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-jersey2 + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-jersey2:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-jersey2-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.FakeApi; + +import java.io.File; +import java.util.*; + +public class FakeApiExample { + + public static void main(String[] args) { + + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + OffsetDateTime dateTime = new OffsetDateTime(); // OffsetDateTime | None + String password = "password_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayTest](docs/ArrayTest.md) + - [Cat](docs/Cat.md) + - [Category](docs/Category.md) + - [Dog](docs/Dog.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/java/jersey2-java8/build.gradle b/samples/client/petstore/java/jersey2-java8/build.gradle new file mode 100644 index 00000000000..ece2fa55d57 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/build.gradle @@ -0,0 +1,113 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-jersey2' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.8" + jackson_version = "2.7.5" + jersey_version = "2.22.2" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/jersey2-java8/build.sbt b/samples/client/petstore/java/jersey2-java8/build.sbt new file mode 100644 index 00000000000..b187fb67ae2 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/build.sbt @@ -0,0 +1,24 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-jersey2", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Animal.md b/samples/client/petstore/java/jersey2-java8/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/AnimalFarm.md b/samples/client/petstore/java/jersey2-java8/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2-java8/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2-java8/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/ArrayTest.md b/samples/client/petstore/java/jersey2-java8/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Cat.md b/samples/client/petstore/java/jersey2-java8/docs/Cat.md new file mode 100644 index 00000000000..6e9f71ce7dd --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Cat.md @@ -0,0 +1,10 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Category.md b/samples/client/petstore/java/jersey2-java8/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/Client.md b/samples/client/petstore/java/jersey2-java8/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Dog.md b/samples/client/petstore/java/jersey2-java8/docs/Dog.md new file mode 100644 index 00000000000..ac7cea323ff --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Dog.md @@ -0,0 +1,10 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/EnumArrays.md b/samples/client/petstore/java/jersey2-java8/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/EnumClass.md b/samples/client/petstore/java/jersey2-java8/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md new file mode 100644 index 00000000000..48dd79dd0e3 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -0,0 +1,187 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +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 + + + +# **testClientModel** +> Client testClientModel(body) + +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) + +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 = B; // 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 +try { + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); +} 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] + +### 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 + +### 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) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | 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** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/jersey2-java8/docs/FormatTest.md b/samples/client/petstore/java/jersey2-java8/docs/FormatTest.md new file mode 100644 index 00000000000..ba089e5a561 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey2-java8/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/MapTest.md b/samples/client/petstore/java/jersey2-java8/docs/MapTest.md new file mode 100644 index 00000000000..714a97a40d9 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..c0bc277c74c --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md new file mode 100644 index 00000000000..5b3a9a0e46d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/ModelApiResponse.md b/samples/client/petstore/java/jersey2-java8/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/ModelReturn.md b/samples/client/petstore/java/jersey2-java8/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Name.md b/samples/client/petstore/java/jersey2-java8/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/NumberOnly.md b/samples/client/petstore/java/jersey2-java8/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/Order.md b/samples/client/petstore/java/jersey2-java8/docs/Order.md new file mode 100644 index 00000000000..268c617d1ff --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/Pet.md b/samples/client/petstore/java/jersey2-java8/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/PetApi.md b/samples/client/petstore/java/jersey2-java8/docs/PetApi.md new file mode 100644 index 00000000000..3b5f84043e3 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> 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/jersey2-java8/docs/ReadOnlyFirst.md b/samples/client/petstore/java/jersey2-java8/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md b/samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/StoreApi.md b/samples/client/petstore/java/jersey2-java8/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> 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>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Tag.md b/samples/client/petstore/java/jersey2-java8/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/User.md b/samples/client/petstore/java/jersey2-java8/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/docs/UserApi.md b/samples/client/petstore/java/jersey2-java8/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> 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/jersey2-java8/git_push.sh b/samples/client/petstore/java/jersey2-java8/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/gradle.properties b/samples/client/petstore/java/jersey2-java8/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/jersey2-java8/gradlew b/samples/client/petstore/java/jersey2-java8/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/jersey2-java8/gradlew.bat b/samples/client/petstore/java/jersey2-java8/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml new file mode 100644 index 00000000000..59cf0ab156d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -0,0 +1,182 @@ + + 4.0.0 + io.swagger + swagger-petstore-jersey2 + jar + swagger-petstore-jersey2 + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + 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 + 2.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.9 + 2.22.2 + 2.7.5 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/jersey2-java8/settings.gradle b/samples/client/petstore/java/jersey2-java8/settings.gradle new file mode 100644 index 00000000000..498d426abee --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-jersey2" \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml b/samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..dc056fe3b7c --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,706 @@ +package io.swagger.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + + +public class ApiClient { + private Map defaultHeaderMap = new HashMap(); + private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; + private String tempFolderPath = null; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.json.setDateFormat((DateFormat) dateFormat.clone()); + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + */ + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } else { + // We let jersey handle the serialization + entity = Entity.entity(obj, contentType); + } + return entity; + } + + /** + * Deserialize response body to Java object according to the Content-Type. + */ + public T deserialize(Response response, GenericType returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.equals(File.class)) { + // Handle file downloading. + @SuppressWarnings("unchecked") + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath()); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity entity = serialize(body, formParams, contentType); + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + return ClientBuilder.newClient(clientConfig); + } + + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..02a967d8373 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..57e53b2d598 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..d0feb432d99 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,36 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.jsr310.*; + +import java.text.DateFormat; + +import javax.ws.rs.ext.ContextResolver; + + +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JavaTimeModule()); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..9ad2d246519 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..31140c76df4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,67 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class 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/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 new file mode 100644 index 00000000000..4a0a926dfc8 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,229 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.Client; +import java.time.OffsetDateTime; +import java.time.LocalDate; +import java.math.BigDecimal; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * To test \"client\" model + * + * @param body client model (required) + * @return Client + * @throws ApiException if fails to make API call + */ + public Client testClientModel(Client body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling testClientModel"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException if fails to make API call + */ + 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) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); +if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); +if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} 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 new file mode 100644 index 00000000000..ad66598406d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,384 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.Pet; +import io.swagger.client.model.ModelApiResponse; +import java.io.File; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void addPet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException if fails to make API call + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet getPetById(Long petId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException if fails to make API call + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (name != null) + localVarFormParams.put("name", name); +if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException if fails to make API call + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); +if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..c0c9a166ad7 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,196 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.Order; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteOrder(String orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + * @throws ApiException if fails to make API call + */ + public Map getInventory() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order getOrderById(Long orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..7602f4e2ba9 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,370 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException if fails to make API call + */ + public void createUser(User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithListInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteUser(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException if fails to make API call + */ + public User getUserByName(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException if fails to make API call + */ + public String loginUser(String username, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs out current logged in user session + * + * @throws ApiException if fails to make API call + */ + public void logoutUser() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException if fails to make API call + */ + public void updateUser(String username, User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..0e0fdb63fb3 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,87 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..0ff06e3b86f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..420178c112d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,70 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import com.migcomponents.migbase64.Base64; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..c1b64913ab8 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..18c25738e0f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} 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 new file mode 100644 index 00000000000..2da13804a0d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..346da224ad1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,123 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Animal + */ + +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(example = "null", 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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..563476ccb3d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,76 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + 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 new file mode 100644 index 00000000000..a99f2009385 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", 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/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 new file mode 100644 index 00000000000..1aaf27b9921 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", 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/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 new file mode 100644 index 00000000000..124d8bfa3a1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..41dc312a10f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java @@ -0,0 +1,102 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..ba4ce89c297 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,123 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..43ade4b6fcb --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..788aee5c226 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java @@ -0,0 +1,102 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/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 new file mode 100644 index 00000000000..45295c524f6 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,190 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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; + } + + @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; + } + + @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 = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..f9887c69340 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = 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/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..a7268316c40 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,236 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = 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; + } + + @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; + } + + @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; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..17f85c6739f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,389 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.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 String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(example = "null", 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.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d874a545244 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,105 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", 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/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 new file mode 100644 index 00000000000..f8cf1ad5d1a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", 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/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 new file mode 100644 index 00000000000..1a70a3aa1dd --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", 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) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..8f48dd8020e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..70ee2a834c0 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,146 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..28294a15090 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..4b70e8df1a6 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,152 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..ad74058d2e5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..87db4c744d8 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,248 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.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; + } + + @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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/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 new file mode 100644 index 00000000000..a89e0ea3e05 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,261 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = 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(example = "null", 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(example = "null", 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(example = "null", 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) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..63e11bf14fd --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,114 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..f8c5c06ca40 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..27be94678da --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,123 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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/jersey2-java8/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..84e3b147049 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,261 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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/jersey2-java8/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 00000000000..7ddf142426e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 00000000000..19b55257d0c --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,239 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 00000000000..b95eb74605e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 00000000000..5286976a819 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,45 @@ +package io.swagger.client; + +import io.swagger.client.model.Order; + +import java.lang.Exception; + +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import org.junit.*; +import static org.junit.Assert.*; + + +public class JSONTest { + JSON json = null; + Order order = null; + + @Before + public void setup() { + json = new JSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 00000000000..4b03c7a9812 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..1ea1e270634 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import java.time.OffsetDateTime; +import java.time.LocalDate; +import java.math.BigDecimal; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + OffsetDateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..7f4d27c8b77 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,288 @@ +package io.swagger.client.api; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + /* + @Test + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); + + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); + + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + assertTrue(categoryIdObj instanceof Integer); + Integer categoryIdInt = (Integer) categoryIdObj; + assertEquals(category.getId(), Long.valueOf(categoryIdInt)); + assertEquals(category.getName(), categoryMap.get("name")); + } + */ + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..1d670975dd6 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,100 @@ +package io.swagger.client.api; + +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; +import java.time.ZoneId; +import java.util.Map; +import java.text.SimpleDateFormat; + +import java.time.OffsetDateTime; +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + /* + @Test + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); + + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + assertTrue(firstEntry.getValue() instanceof Integer); + } + */ + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().toInstant(), fetched.getShipDate().toInstant()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(OffsetDateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..c7fb92d2552 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,88 @@ +package io.swagger.client.api; + +import io.swagger.TestUtils; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 00000000000..5bdb4fb78fb --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 00000000000..52c5497ba83 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/jersey2/.travis.yml b/samples/client/petstore/java/jersey2/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/jersey2/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: 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/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 33280cd3e67..067c81e1645 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -94,9 +94,9 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "2.22.2" - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" junit_version = "4.12" } @@ -104,11 +104,11 @@ dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.glassfish.jersey.core:jersey-client:$jersey_version" compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" compile "joda-time:joda-time:$jodatime_version" compile "com.brsanthu:migbase64:2.2" testCompile "junit:junit:$junit_version" diff --git a/samples/client/petstore/java/jersey2/build.sbt b/samples/client/petstore/java/jersey2/build.sbt index 08a215edacf..555b44f16db 100644 --- a/samples/client/petstore/java/jersey2/build.sbt +++ b/samples/client/petstore/java/jersey2/build.sbt @@ -12,12 +12,12 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.8", "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", - "joda-time" % "joda-time" % "2.9.3", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", + "joda-time" % "joda-time" % "2.9.4", "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/jersey2/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/jersey2/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/jersey2/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/jersey2/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/jersey2/docs/Cat.md b/samples/client/petstore/java/jersey2/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/jersey2/docs/Cat.md +++ b/samples/client/petstore/java/jersey2/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/Client.md b/samples/client/petstore/java/jersey2/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/Dog.md b/samples/client/petstore/java/jersey2/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/jersey2/docs/Dog.md +++ b/samples/client/petstore/java/jersey2/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/EnumArrays.md b/samples/client/petstore/java/jersey2/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/jersey2/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/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index 0c1f55a0902..9012aff618e 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -4,12 +4,57 @@ All URIs are relative to *http://petstore.swagger.io/v2* 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 + +# **testClientModel** +> Client testClientModel(body) + +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, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -18,25 +63,35 @@ 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 string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -49,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| 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** | **DateTime**| None | [optional] @@ -66,10 +122,66 @@ null (empty response body) ### Authorization -No authorization required +[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 + +### 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) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | 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** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/jersey2/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey2/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/jersey2/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/jersey2/docs/MapTest.md b/samples/client/petstore/java/jersey2/docs/MapTest.md new file mode 100644 index 00000000000..714a97a40d9 --- /dev/null +++ b/samples/client/petstore/java/jersey2/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/jersey2/docs/Model200Response.md b/samples/client/petstore/java/jersey2/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/jersey2/docs/Model200Response.md +++ b/samples/client/petstore/java/jersey2/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/NumberOnly.md b/samples/client/petstore/java/jersey2/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/jersey2/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/jersey2/docs/PetApi.md b/samples/client/petstore/java/jersey2/docs/PetApi.md index e0314e20e51..3b5f84043e3 100644 --- a/samples/client/petstore/java/jersey2/docs/PetApi.md +++ b/samples/client/petstore/java/jersey2/docs/PetApi.md @@ -158,7 +158,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] ### Return type diff --git a/samples/client/petstore/java/jersey2/gradlew.bat b/samples/client/petstore/java/jersey2/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/jersey2/gradlew.bat +++ b/samples/client/petstore/java/jersey2/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 1d15ec27814..4cae9e4ce95 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -98,12 +98,17 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 2.5.1 1.7 1.7 + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -127,7 +132,7 @@ org.glassfish.jersey.media jersey-media-json-jackson - 2.22.1 + ${jersey-version} @@ -149,7 +154,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -173,10 +178,10 @@ - 1.5.8 + 1.5.9 2.22.2 - 2.7.0 - 2.9.3 + 2.7.5 + 2.9.4 1.0.0 4.12 diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 047a47252f8..ec4fea20fad 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,6 @@ import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -70,14 +69,7 @@ public ApiClient() { json = new JSON(); httpClient = buildHttpClient(debugging); - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.dateFormat = new RFC3339DateFormat(); // Set default User-Agent. setUserAgent("Swagger-Codegen/1.0.0/java"); @@ -85,6 +77,7 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); @@ -497,8 +490,15 @@ public Entity serialize(Object obj, Map formParams, String co * Deserialize response body to Java object according to the Content-Type. */ public T deserialize(Response response, GenericType returnType) throws ApiException { - // Handle file downloading. - if (returnType.equals(File.class)) { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.equals(File.class)) { + // Handle file downloading. @SuppressWarnings("unchecked") T file = (T) downloadFileFromResponse(response); return file; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index 600bb507f09..02a967d8373 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index cbdadd6262d..57e53b2d598 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index d6f725b2caa..126fa1c856a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -19,6 +19,7 @@ public JSON() { mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); mapper.registerModule(new JodaModule()); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index 4b44c415812..9ad2d246519 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..3d287008be5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.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/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..31140c76df4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/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 b8b499c4dee..70d8b276c1c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -7,9 +7,10 @@ import javax.ws.rs.core.GenericType; +import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -36,24 +37,66 @@ public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } + /** + * To test \"client\" model + * + * @param body client model (required) + * @return Client + * @throws ApiException if fails to make API call + */ + public Client testClientModel(Client body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling testClientModel"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + 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, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -66,9 +109,9 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); } // verify the required parameter '_byte' is set @@ -100,6 +143,8 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str localVarFormParams.put("double", _double); if (string != null) localVarFormParams.put("string", string); +if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); if (_byte != null) localVarFormParams.put("byte", _byte); if (binary != null) @@ -121,9 +166,64 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { }; + String[] localVarAuthNames = new String[] { "http_basic_test" }; apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); +if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); +if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } 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 ab85c4ac394..ad66598406d 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 @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6ba15566b60..0e0fdb63fb3 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -78,9 +78,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index a063a6998b5..0ff06e3b86f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 5895370e4d4..420178c112d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index 8802ebc92c8..c1b64913ab8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..18c25738e0f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ccaba7709c4..2da13804a0d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -15,40 +40,54 @@ */ public class AdditionalPropertiesClass { - + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; } - + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - - /** - **/ public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; return this; } - + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 25c7d3e421c..346da224ad1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +37,44 @@ */ 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(example = "null", required = true, value = "") - @JsonProperty("className") 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(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index 647e3a893e1..563476ccb3d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,6 +1,30 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -12,9 +36,7 @@ */ public class AnimalFarm extends ArrayList { - - @Override public boolean equals(java.lang.Object o) { if (this == o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..a99f2009385 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..1aaf27b9921 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,108 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 6c1eb23d8d0..124d8bfa3a1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,10 +1,36 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; @@ -14,58 +40,80 @@ */ public class ArrayTest { - + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } - + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - - /** - **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } - + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - - /** - **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index 5ef9e23bd96..41dc312a10f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +38,23 @@ */ public class Cat extends Animal { - - private String className = null; - private String color = "red"; + @JsonProperty("declawed") private Boolean declawed = null; - - /** - **/ - public Cat className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Cat color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - /** - **/ public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; } - + + /** + * Get declawed + * @return declawed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } @@ -79,15 +69,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -95,8 +83,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index c6cb703a89e..ba4ce89c297 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +37,44 @@ */ 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(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Category name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..43ade4b6fcb --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index 4b3cc947cc5..788aee5c226 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +38,23 @@ */ public class Dog extends Animal { - - private String className = null; - private String color = "red"; + @JsonProperty("breed") private String breed = null; - - /** - **/ - public Dog className(String className) { - this.className = className; - return this; - } - - @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - - /** - **/ - public Dog color(String color) { - this.color = color; - return this; - } - - @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - /** - **/ public Dog breed(String breed) { this.breed = breed; return this; } - + + /** + * Get breed + * @return breed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } @@ -79,15 +69,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -95,8 +83,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..45295c524f6 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,190 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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; + } + + @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; + } + + @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 = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java index 42434e297ff..f9887c69340 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,16 +1,44 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; + /** * Gets or Sets EnumClass */ public enum EnumClass { + _ABC("_abc"), + _EFG("-efg"), + _XYZ_("(xyz)"); private String value; @@ -20,9 +48,18 @@ public enum EnumClass { } @Override - @JsonValue 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/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 1c8657fd3ec..a7268316c40 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,9 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,13 +37,12 @@ */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { UPPER("UPPER"), + LOWER("lower"); private String value; @@ -29,12 +52,22 @@ public enum EnumStringEnum { } @Override - @JsonValue 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; /** @@ -42,6 +75,7 @@ public String toString() { */ public enum EnumIntegerEnum { NUMBER_1(1), + NUMBER_MINUS_1(-1); private Integer value; @@ -51,12 +85,22 @@ public enum EnumIntegerEnum { } @Override - @JsonValue 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; /** @@ -64,6 +108,7 @@ public String toString() { */ public enum EnumNumberEnum { NUMBER_1_DOT_1(1.1), + NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -73,61 +118,74 @@ public enum EnumNumberEnum { } @Override - @JsonValue 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; - - /** - **/ public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; } - + + /** + * Get enumString + * @return enumString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") 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(example = "null", value = "") - @JsonProperty("enum_integer") 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(example = "null", value = "") - @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index 79376150017..2b5b4204281 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -15,248 +40,285 @@ */ 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 DateTime dateTime = null; + + @JsonProperty("uuid") private String uuid = null; + + @JsonProperty("password") private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } - + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } - + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") 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(example = "null", value = "") - @JsonProperty("int64") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } - + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ public FormatTest _float(Float _float) { this._float = _float; return this; } - + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ public FormatTest _double(Double _double) { this._double = _double; return this; } - + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") 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(example = "null", value = "") - @JsonProperty("string") 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(example = "null", required = true, value = "") - @JsonProperty("byte") 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(example = "null", value = "") - @JsonProperty("binary") 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(example = "null", required = true, value = "") - @JsonProperty("date") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - - /** - **/ public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public FormatTest uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public FormatTest password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d874a545244 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,105 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..f8cf1ad5d1a --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2f0972bf41e..20958fd50d8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -17,58 +42,70 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - + @JsonProperty("uuid") private String uuid = null; + + @JsonProperty("dateTime") private DateTime dateTime = null; + + @JsonProperty("map") private Map map = new HashMap(); - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; return this; } - + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index eed3902b922..8f48dd8020e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,42 +38,46 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - + @JsonProperty("name") private Integer name = null; - private String PropertyClass = null; - - /** - **/ + @JsonProperty("class") + private String propertyClass = null; + public Model200Response name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - - /** - **/ - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } - + + /** + * Get propertyClass + * @return propertyClass + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("class") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -62,12 +91,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -76,7 +105,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 32fb86dd323..70ee2a834c0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,58 +37,65 @@ */ 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(example = "null", value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + + /** + * Get type + * @return type + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + + /** + * Get message + * @return message + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index a076d16f964..28294a15090 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,22 +38,23 @@ @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(example = "null", value = "") - @JsonProperty("return") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index 1ba2cc5e4a3..4b70e8df1a6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,56 +38,68 @@ @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(example = "null", required = true, value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - + /** + * Get snakeCase + * @return snakeCase + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - - /** - **/ public Name property(String property) { this.property = property; return this; } - + + /** + * Get property + * @return property + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - + /** + * Get _123Number + * @return _123Number + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..ad74058d2e5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +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(example = "null", 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/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index cec651e73a6..1616b030b9d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -14,10 +38,16 @@ */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; + + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -25,7 +55,9 @@ public class Order { */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -35,114 +67,131 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + + @JsonProperty("complete") private Boolean complete = false; - - /** - **/ public Order id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + + /** + * Get petId + * @return petId + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + + /** + * Order Status + * @return status + **/ @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + + /** + * Get complete + * @return complete + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index da8b76ad024..a89e0ea3e05 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -1,9 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -17,11 +41,19 @@ */ 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 = new ArrayList(); /** @@ -29,7 +61,9 @@ public class Pet { */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -39,113 +73,138 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; - - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + + /** + * Get category + * @return category + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - - /** - **/ public Pet name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index fdc3587df0e..63e11bf14fd 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,30 +37,35 @@ */ public class ReadOnlyFirst { - + @JsonProperty("bar") private String bar = null; + + @JsonProperty("baz") private String baz = null; - + /** + * Get bar + * @return bar + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") public String getBar() { return bar; } - - /** - **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; } - + + /** + * Get baz + * @return baz + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index 24e57756cb2..f8c5c06ca40 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,22 +37,23 @@ */ 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(example = "null", value = "") - @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 9d3bdd8cb9e..27be94678da 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +37,44 @@ */ 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(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Tag name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index f23553660de..84e3b147049 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -1,8 +1,33 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,149 +37,170 @@ */ 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(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public User username(String username) { this.username = username; return this; } - + + /** + * Get username + * @return username + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - - /** - **/ public User email(String email) { this.email = email; return this; } - + + /** + * Get email + * @return email + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - - /** - **/ public User password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + + /** + * Get phone + * @return phone + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java index 9386b3d5236..78556e36639 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -1,8 +1,11 @@ package io.swagger.client; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ser.std.SqlDateSerializer; import io.swagger.client.model.Order; import java.lang.Exception; +import java.sql.Date; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; @@ -17,7 +20,7 @@ public class JSONTest { @Before public void setup() { - json = new JSON(); + json = new ApiClient().getJSON(); order = new Order(); } @@ -42,4 +45,18 @@ public void testCustomDate() throws Exception { Order o = json.getContext(null).readValue(str, Order.class); assertEquals(dateStr, dateFormat.print(o.getShipDate())); } + + @Test + public void testSqlDateSerialization() throws Exception { + String str = json.getContext(null).writeValueAsString(new java.sql.Date(10)); + assertEquals("\"1970-01-01\"", str); + } + + @Test + public void testSqlDateDeserialization() throws Exception { + final String str = "1970-01-01"; + java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class); + assertEquals(date.toString(), str); + } + } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 00000000000..867c454bff6 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,62 @@ +package io.swagger.client.model; + +import java.io.StringWriter; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.SerializationFeature.*; + +public class EnumValueTest { + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\"}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/.gitignore b/samples/client/petstore/java/okhttp-gson-parcelableModel/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/.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/okhttp-gson-parcelableModel/.swagger-codegen-ignore b/samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/.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/okhttp-gson-parcelableModel/.travis.yml b/samples/client/petstore/java/okhttp-gson-parcelableModel/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: 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/okhttp-gson-parcelableModel/LICENSE b/samples/client/petstore/java/okhttp-gson-parcelableModel/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md new file mode 100644 index 00000000000..8266ae87a9c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md @@ -0,0 +1,183 @@ +# swagger-petstore-okhttp-gson + +## 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-okhttp-gson + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-okhttp-gson:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-okhttp-gson-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.FakeApi; + +import java.io.File; +import java.util.*; + +public class FakeApiExample { + + public static void main(String[] args) { + + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + DateTime dateTime = new DateTime(); // DateTime | None + String password = "password_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Cat](docs/Cat.md) + - [Category](docs/Category.md) + - [Dog](docs/Dog.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [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) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin 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 issue. + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle new file mode 100644 index 00000000000..d7c6b63ea75 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle @@ -0,0 +1,103 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +dependencies { + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' + testCompile 'junit:junit:4.12' +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt new file mode 100644 index 00000000000..01a1095f8a4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-okhttp-gson", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Animal.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/AnimalFarm.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Category.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/Dog.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumClass.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md new file mode 100644 index 00000000000..21a4db7c377 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md @@ -0,0 +1,122 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/MapTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MapTest.md @@ -0,0 +1,17 @@ + +# 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 +---- | ----- + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Model200Response.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Model200Response.md new file mode 100644 index 00000000000..b47618b28cc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/ModelApiResponse.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/ModelReturn.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Name.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/NumberOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/Order.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Pet.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/PetApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/PetApi.md new file mode 100644 index 00000000000..e0314e20e51 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> 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 | + +### 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/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> 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>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Tag.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/User.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/docs/UserApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> 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/okhttp-gson-parcelableModel/git_push.sh b/samples/client/petstore/java/okhttp-gson-parcelableModel/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/gradle.properties b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/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/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew.bat b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml new file mode 100644 index 00000000000..9998f398c10 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml @@ -0,0 +1,168 @@ + + 4.0.0 + io.swagger + petstore-okhttp-gson-parcelable + jar + petstore-okhttp-gson-parcelable + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + gradle-test + integration-test + + exec + + + gradle + + test + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + com.squareup.okhttp + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + joda-time + joda-time + ${jodatime-version} + + + + + junit + junit + ${junit-version} + test + + + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 2.7.5 + 2.6.2 + 2.9.3 + 1.0.0 + 4.12 + UTF-8 + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/settings.gradle b/samples/client/petstore/java/okhttp-gson-parcelableModel/settings.gradle new file mode 100644 index 00000000000..b73eec84591 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-okhttp-gson" \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..a2460c37ee3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..c4137dcb816 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,1327 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +public class ApiClient { + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; + + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; + } + + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient + */ + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..02a967d8373 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..b87ea49a02e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..57e53b2d598 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Configuration.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..a734bec47f1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,236 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param context Json Serialization Context + * @return Date + * @throws JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..9ad2d246519 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..fee9da83ddd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressRequestBody.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..761a23a2869 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..31140c76df4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,67 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class 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/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 new file mode 100644 index 00000000000..975bd34004c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,495 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Client; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testClientModel */ + private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "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, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test \"client\" model + * + * @param body client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Client testClientModel(Client body) throws ApiException { + ApiResponse resp = testClientModelWithHttpInfo(body); + return resp.getData(); + } + + /** + * To test \"client\" model + * + * @param body client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { + com.squareup.okhttp.Call call = testClientModelCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * To test \"client\" model (asynchronously) + * + * @param body client model (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 testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for testEndpointParameters */ + private 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, DateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(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 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumParameters */ + private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryStringArray != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + if (enumQueryString != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); + if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + Map localVarFormParams = new HashMap(); + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + 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, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum parameters (asynchronously) + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param 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 testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, 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 = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + 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 new file mode 100644 index 00000000000..aca7f0b02b0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,935 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + 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 = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + 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 = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + 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 = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-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 new file mode 100644 index 00000000000..04ad8deb2a6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + 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 = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-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 new file mode 100644 index 00000000000..adcdda4b6d1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,907 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + 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 = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + 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 = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..0e0fdb63fb3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,87 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..0ff06e3b86f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..d54692966a9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,66 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import com.squareup.okhttp.Credentials; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..c1b64913ab8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuth.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..18c25738e0f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..437a78be54c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -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 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass implements Parcelable { + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(mapProperty); + + out.writeValue(mapOfMapProperty); + } + + public AdditionalPropertiesClass() { + super(); + } + + AdditionalPropertiesClass(Parcel in) { + + mapProperty = (Map)in.readValue(null); + mapOfMapProperty = (Map>)in.readValue(Map.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AdditionalPropertiesClass createFromParcel(Parcel in) { + return new AdditionalPropertiesClass(in); + } + public AdditionalPropertiesClass[] newArray(int size) { + return new AdditionalPropertiesClass[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..4329ce2253c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,153 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Animal + */ + +public class Animal implements Parcelable { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(className); + + out.writeValue(color); + } + + public Animal() { + super(); + } + + Animal(Parcel in) { + + className = (String)in.readValue(null); + color = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Animal createFromParcel(Parcel in) { + return new Animal(in); + } + public Animal[] newArray(int size) { + return new Animal[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..81d9cba7996 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList implements Parcelable { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); } + + public AnimalFarm() { + super(); + } + + AnimalFarm(Parcel in) { + super(in); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AnimalFarm createFromParcel(Parcel in) { + return new AnimalFarm(in); + } + public AnimalFarm[] newArray(int size) { + return new AnimalFarm[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..cbf5aaebacb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,135 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly implements Parcelable { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(arrayArrayNumber); + } + + public ArrayOfArrayOfNumberOnly() { + super(); + } + + ArrayOfArrayOfNumberOnly(Parcel in) { + + arrayArrayNumber = (List>)in.readValue(List.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArrayOfArrayOfNumberOnly createFromParcel(Parcel in) { + return new ArrayOfArrayOfNumberOnly(in); + } + public ArrayOfArrayOfNumberOnly[] newArray(int size) { + return new ArrayOfArrayOfNumberOnly[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..f714b7660b7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,135 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly implements Parcelable { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(arrayNumber); + } + + public ArrayOfNumberOnly() { + super(); + } + + ArrayOfNumberOnly(Parcel in) { + + arrayNumber = (List)in.readValue(BigDecimal.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArrayOfNumberOnly createFromParcel(Parcel in) { + return new ArrayOfNumberOnly(in); + } + public ArrayOfNumberOnly[] newArray(int size) { + return new ArrayOfNumberOnly[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..c90ada4e4db --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,197 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * ArrayTest + */ + +public class ArrayTest implements Parcelable { + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(arrayOfString); + + out.writeValue(arrayArrayOfInteger); + + out.writeValue(arrayArrayOfModel); + } + + public ArrayTest() { + super(); + } + + ArrayTest(Parcel in) { + + arrayOfString = (List)in.readValue(null); + arrayArrayOfInteger = (List>)in.readValue(List.class.getClassLoader()); + arrayArrayOfModel = (List>)in.readValue(List.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArrayTest createFromParcel(Parcel in) { + return new ArrayTest(in); + } + public ArrayTest[] newArray(int size) { + return new ArrayTest[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..b2de1391b39 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Cat + */ + +public class Cat extends Animal implements Parcelable { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + +>>>>>>> fix bug with parcelable:samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java + @SerializedName("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(example = "null", value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeValue(className); + + out.writeValue(color); + + out.writeValue(declawed); + } + + public Cat() { + super(); + } + + Cat(Parcel in) { + super(in); + className = (String)in.readValue(null); + color = (String)in.readValue(null); + declawed = (Boolean)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Cat createFromParcel(Parcel in) { + return new Cat(in); + } + public Cat[] newArray(int size) { + return new Cat[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..ae9a59adc9e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,153 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Category + */ + +public class Category implements Parcelable { + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(name); + } + + public Category() { + super(); + } + + Category(Parcel in) { + + id = (Long)in.readValue(null); + name = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Category createFromParcel(Parcel in) { + return new Category(in); + } + public Category[] newArray(int size) { + return new Category[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..3e74dcb15ad --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Dog + */ + +public class Dog extends Animal implements Parcelable { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + +>>>>>>> fix bug with parcelable:samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java + @SerializedName("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeValue(className); + + out.writeValue(color); + + out.writeValue(breed); + } + + public Dog() { + super(); + } + + Dog(Parcel in) { + super(in); + className = (String)in.readValue(null); + color = (String)in.readValue(null); + breed = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Dog createFromParcel(Parcel in) { + return new Dog(in); + } + public Dog[] newArray(int size) { + return new Dog[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..9bbb91b93ae --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumClass.java @@ -0,0 +1,59 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import android.os.Parcelable; +import android.os.Parcel; + + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + @SerializedName("_abc") + _ABC("_abc"), + + @SerializedName("-efg") + _EFG("-efg"), + + @SerializedName("(xyz)") + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..ce94e934b17 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,245 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * EnumTest + */ + +public class EnumTest implements Parcelable { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + @SerializedName("1") + NUMBER_1(1), + + @SerializedName("-1") + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + @SerializedName("1.1") + NUMBER_1_DOT_1(1.1), + + @SerializedName("-1.2") + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("enum_number") + private EnumNumberEnum enumNumber = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(enumString); + + out.writeValue(enumInteger); + + out.writeValue(enumNumber); + } + + public EnumTest() { + super(); + } + + EnumTest(Parcel in) { + + enumString = (EnumStringEnum)in.readValue(null); + enumInteger = (EnumIntegerEnum)in.readValue(null); + enumNumber = (EnumNumberEnum)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public EnumTest createFromParcel(Parcel in) { + return new EnumTest(in); + } + public EnumTest[] newArray(int size) { + return new EnumTest[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..6da8e63693d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,452 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * FormatTest + */ + +public class FormatTest implements Parcelable { + @SerializedName("integer") + private Integer integer = null; + + @SerializedName("int32") + private Integer int32 = null; + + @SerializedName("int64") + private Long int64 = null; + + @SerializedName("number") + private BigDecimal number = null; + + @SerializedName("float") + private Float _float = null; + + @SerializedName("double") + private Double _double = null; + + @SerializedName("string") + private String string = null; + + @SerializedName("byte") + private byte[] _byte = null; + + @SerializedName("binary") + private byte[] binary = null; + + @SerializedName("date") + private LocalDate date = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(example = "null", 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.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(integer); + + out.writeValue(int32); + + out.writeValue(int64); + + out.writeValue(number); + + out.writeValue(_float); + + out.writeValue(_double); + + out.writeValue(string); + + out.writeValue(_byte); + + out.writeValue(binary); + + out.writeValue(date); + + out.writeValue(dateTime); + + out.writeValue(uuid); + + out.writeValue(password); + } + + public FormatTest() { + super(); + } + + FormatTest(Parcel in) { + + integer = (Integer)in.readValue(null); + int32 = (Integer)in.readValue(null); + int64 = (Long)in.readValue(null); + number = (BigDecimal)in.readValue(null); + _float = (Float)in.readValue(null); + _double = (Double)in.readValue(null); + string = (String)in.readValue(null); + _byte = (byte[])in.readValue(null); + binary = (byte[])in.readValue(null); + date = (LocalDate)in.readValue(null); + dateTime = (DateTime)in.readValue(null); + uuid = (String)in.readValue(null); + password = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public FormatTest createFromParcel(Parcel in) { + return new FormatTest(in); + } + public FormatTest[] newArray(int size) { + return new FormatTest[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..287bada323c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,135 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly implements Parcelable { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(bar); + + out.writeValue(foo); + } + + public HasOnlyReadOnly() { + super(); + } + + HasOnlyReadOnly(Parcel in) { + + bar = (String)in.readValue(null); + foo = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public HasOnlyReadOnly createFromParcel(Parcel in) { + return new HasOnlyReadOnly(in); + } + public HasOnlyReadOnly[] newArray(int size) { + return new HasOnlyReadOnly[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..61e6fff8e4b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,188 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * MapTest + */ + +public class MapTest implements Parcelable { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(mapMapOfString); + + out.writeValue(mapOfEnumString); + } + + public MapTest() { + super(); + } + + MapTest(Parcel in) { + + mapMapOfString = (Map>)in.readValue(Map.class.getClassLoader()); + mapOfEnumString = (Map)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public MapTest createFromParcel(Parcel in) { + return new MapTest(in); + } + public MapTest[] newArray(int size) { + return new MapTest[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..5121e62791b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,189 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass implements Parcelable { + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(uuid); + + out.writeValue(dateTime); + + out.writeValue(map); + } + + public MixedPropertiesAndAdditionalPropertiesClass() { + super(); + } + + MixedPropertiesAndAdditionalPropertiesClass(Parcel in) { + + uuid = (String)in.readValue(null); + dateTime = (DateTime)in.readValue(null); + map = (Map)in.readValue(Animal.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public MixedPropertiesAndAdditionalPropertiesClass createFromParcel(Parcel in) { + return new MixedPropertiesAndAdditionalPropertiesClass(in); + } + public MixedPropertiesAndAdditionalPropertiesClass[] newArray(int size) { + return new MixedPropertiesAndAdditionalPropertiesClass[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..ba5997cc7dc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,154 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response implements Parcelable { + @SerializedName("name") + private Integer name = null; + + @SerializedName("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(name); + + out.writeValue(PropertyClass); + } + + public Model200Response() { + super(); + } + + Model200Response(Parcel in) { + + name = (Integer)in.readValue(null); + PropertyClass = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Model200Response createFromParcel(Parcel in) { + return new Model200Response(in); + } + public Model200Response[] newArray(int size) { + return new Model200Response[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..573f8c5a6ab --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,179 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse implements Parcelable { + @SerializedName("code") + private Integer code = null; + + @SerializedName("type") + private String type = null; + + @SerializedName("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(code); + + out.writeValue(type); + + out.writeValue(message); + } + + public ModelApiResponse() { + super(); + } + + ModelApiResponse(Parcel in) { + + code = (Integer)in.readValue(null); + type = (String)in.readValue(null); + message = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ModelApiResponse createFromParcel(Parcel in) { + return new ModelApiResponse(in); + } + public ModelApiResponse[] newArray(int size) { + return new ModelApiResponse[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..1d9cdbc1f05 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,128 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn implements Parcelable { + @SerializedName("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(_return); + } + + public ModelReturn() { + super(); + } + + ModelReturn(Parcel in) { + + _return = (Integer)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ModelReturn createFromParcel(Parcel in) { + return new ModelReturn(in); + } + public ModelReturn[] newArray(int size) { + return new ModelReturn[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..94c4fa78b05 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,188 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name implements Parcelable { + @SerializedName("name") + private Integer name = null; + + @SerializedName("snake_case") + private Integer snakeCase = null; + + @SerializedName("property") + private String property = null; + + @SerializedName("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(name); + + out.writeValue(snakeCase); + + out.writeValue(property); + + out.writeValue(_123Number); + } + + public Name() { + super(); + } + + Name(Parcel in) { + + name = (Integer)in.readValue(null); + snakeCase = (Integer)in.readValue(null); + property = (String)in.readValue(null); + _123Number = (Integer)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Name createFromParcel(Parcel in) { + return new Name(in); + } + public Name[] newArray(int size) { + return new Name[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..3b8fbd205b8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,128 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * NumberOnly + */ + +public class NumberOnly implements Parcelable { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(justNumber); + } + + public NumberOnly() { + super(); + } + + NumberOnly(Parcel in) { + + justNumber = (BigDecimal)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public NumberOnly createFromParcel(Parcel in) { + return new NumberOnly(in); + } + public NumberOnly[] newArray(int size) { + return new NumberOnly[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..74ea704775c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,283 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Order + */ + +public class Order implements Parcelable { + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(example = "null", 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(example = "null", value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(petId); + + out.writeValue(quantity); + + out.writeValue(shipDate); + + out.writeValue(status); + + out.writeValue(complete); + } + + public Order() { + super(); + } + + Order(Parcel in) { + + id = (Long)in.readValue(null); + petId = (Long)in.readValue(null); + quantity = (Integer)in.readValue(null); + shipDate = (DateTime)in.readValue(null); + status = (StatusEnum)in.readValue(null); + complete = (Boolean)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Order createFromParcel(Parcel in) { + return new Order(in); + } + public Order[] newArray(int size) { + return new Order[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..851cb446cec --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,296 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Pet + */ + +public class Pet implements Parcelable { + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", 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) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(category); + + out.writeValue(name); + + out.writeValue(photoUrls); + + out.writeValue(tags); + + out.writeValue(status); + } + + public Pet() { + super(); + } + + Pet(Parcel in) { + + id = (Long)in.readValue(null); + category = (Category)in.readValue(null); + name = (String)in.readValue(null); + photoUrls = (List)in.readValue(null); + tags = (List)in.readValue(Tag.class.getClassLoader()); + status = (StatusEnum)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Pet createFromParcel(Parcel in) { + return new Pet(in); + } + public Pet[] newArray(int size) { + return new Pet[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..45cde5d0d24 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,144 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst implements Parcelable { + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(bar); + + out.writeValue(baz); + } + + public ReadOnlyFirst() { + super(); + } + + ReadOnlyFirst(Parcel in) { + + bar = (String)in.readValue(null); + baz = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ReadOnlyFirst createFromParcel(Parcel in) { + return new ReadOnlyFirst(in); + } + public ReadOnlyFirst[] newArray(int size) { + return new ReadOnlyFirst[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..8737aa82928 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,127 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * SpecialModelName + */ + +public class SpecialModelName implements Parcelable { + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(specialPropertyName); + } + + public SpecialModelName() { + super(); + } + + SpecialModelName(Parcel in) { + + specialPropertyName = (Long)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public SpecialModelName createFromParcel(Parcel in) { + return new SpecialModelName(in); + } + public SpecialModelName[] newArray(int size) { + return new SpecialModelName[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..67bf5b0d7c7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,153 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * Tag + */ + +public class Tag implements Parcelable { + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(name); + } + + public Tag() { + super(); + } + + Tag(Parcel in) { + + id = (Long)in.readValue(null); + name = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Tag createFromParcel(Parcel in) { + return new Tag(in); + } + public Tag[] newArray(int size) { + return new Tag[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..785747bfbd0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,309 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import android.os.Parcelable; +import android.os.Parcel; + +/** + * User + */ + +public class User implements Parcelable { + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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(example = "null", 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 "); + } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(username); + + out.writeValue(firstName); + + out.writeValue(lastName); + + out.writeValue(email); + + out.writeValue(password); + + out.writeValue(phone); + + out.writeValue(userStatus); + } + + public User() { + super(); + } + + User(Parcel in) { + + id = (Long)in.readValue(null); + username = (String)in.readValue(null); + firstName = (String)in.readValue(null); + lastName = (String)in.readValue(null); + email = (String)in.readValue(null); + password = (String)in.readValue(null); + phone = (String)in.readValue(null); + userStatus = (Integer)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public User createFromParcel(Parcel in) { + return new User(in); + } + public User[] newArray(int size) { + return new User[size]; + } + }; +} + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..5a7d2e5aa80 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + DateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + + /** + * To test enum query parameters + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumQueryParametersTest() throws ApiException { + String enumQueryString = null; + BigDecimal enumQueryInteger = null; + Double enumQueryDouble = null; + // api.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..373f7d287ad --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,180 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet body = null; + // api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + 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 ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + 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 ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet body = null; + // api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + 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/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..4bcdcbf8338 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,108 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Order; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private 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 ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + // 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 ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..832748dbb45 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,174 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.User; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User body = null; + // api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + // api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List body = null; + // api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + // api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User body = null; + // api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/okhttp-gson/docs/Cat.md b/samples/client/petstore/java/okhttp-gson/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Cat.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/Client.md b/samples/client/petstore/java/okhttp-gson/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/Dog.md b/samples/client/petstore/java/okhttp-gson/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Dog.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/EnumArrays.md b/samples/client/petstore/java/okhttp-gson/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index bb52256e6be..29813bd9349 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(testCodeInjectEnd) + +# **testClientModel** +> Client testClientModel(body) -To test code injection =end +To test \"client\" model ### Example ```java @@ -23,11 +23,12 @@ To test code injection =end FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end +Client body = new Client(); // Client | client model try { - apiInstance.testCodeInjectEnd(testCodeInjectEnd); + Client result = apiInstance.testClientModel(body); + System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); + System.err.println("Exception when calling FakeApi#testClientModel"); e.printStackTrace(); } ``` @@ -36,11 +37,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -null (empty response body) +[**Client**](Client.md) ### Authorization @@ -48,12 +49,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -62,25 +63,36 @@ 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 string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + 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(); @@ -93,16 +105,18 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| 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** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type @@ -110,18 +124,18 @@ null (empty response body) ### Authorization -No authorization required +[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 - -# **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -131,13 +145,18 @@ To test enum query parameters 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) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -146,6 +165,11 @@ try { 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** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/MapTest.md b/samples/client/petstore/java/okhttp-gson/docs/MapTest.md index c671e97ffbc..714a97a40d9 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/MapTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/MapTest.md @@ -12,6 +12,8 @@ Name | Type | Description | Notes ## Enum: Map<String, InnerEnum> Name | Value ---- | ----- +UPPER | "UPPER" +LOWER | "lower" diff --git a/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md b/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/PetApi.md b/samples/client/petstore/java/okhttp-gson/docs/PetApi.md index e0314e20e51..3b5f84043e3 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/PetApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/PetApi.md @@ -158,7 +158,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] ### Return type diff --git a/samples/client/petstore/java/okhttp-gson/gradlew.bat b/samples/client/petstore/java/okhttp-gson/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/okhttp-gson/gradlew.bat +++ b/samples/client/petstore/java/okhttp-gson/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 0204c5c96aa..b7b04e3e4c5 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 @@ -812,6 +812,7 @@ public String escapeString(String str) { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -1006,6 +1007,7 @@ public void executeAsync(Call call, ApiCallback callback) { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index a0b9c9c1cf0..540611eab9d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -103,6 +103,7 @@ public String serialize(Object obj) { * @param returnType The type to deserialize inot * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { 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 6d956441b6f..52dce361e2a 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 @@ -67,105 +67,6 @@ public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } - /* Build call for testCodeInjectEnd */ - private com.squareup.okhttp.Call testCodeInjectEndCall(String testCodeInjectEnd, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (testCodeInjectEnd != null) - localVarFormParams.put("test code inject */ =end", testCodeInjectEnd); - - final String[] localVarAccepts = { - "application/json", "*/ end" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "*/ =end'));(phpinfo('" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testCodeInjectEnd(String testCodeInjectEnd) throws ApiException { - testCodeInjectEndWithHttpInfo(testCodeInjectEnd); - } - - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testCodeInjectEndWithHttpInfo(String testCodeInjectEnd) throws ApiException { - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, null, null); - return apiClient.execute(call); - } - - /** - * To test code injection =end (asynchronously) - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testCodeInjectEndAsync(String testCodeInjectEnd, 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 = testCodeInjectEndCall(testCodeInjectEnd, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } /* Build call for testEndpointParameters */ private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..93e0a64052e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -121,5 +120,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..9eb654aa381 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @SerializedName("className") private String className = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..94b3af4bea6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..ad8b7bab8ca 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -98,5 +97,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..1378b3d7d6a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -98,5 +97,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..afd071dbf54 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -48,31 +47,6 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; @@ -127,24 +101,6 @@ public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +113,12 @@ public boolean equals(java.lang.Object o) { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +129,6 @@ public String toString() { 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(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } @@ -189,5 +143,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..fcf291e658c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @SerializedName("className") private String className = null; @@ -143,5 +142,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..aee4cd3c607 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..54a54647918 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,99 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Client + */ + +public class Client { + @SerializedName("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(example = "null", 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/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..a0160714c2f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @SerializedName("className") private String className = null; @@ -143,5 +142,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..c5096738755 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,173 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName(">=") + GREATER_THAN_OR_EQUAL_TO(">="), + + @SerializedName("$") + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + @SerializedName("fish") + FISH("fish"), + + @SerializedName("crab") + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..2f93aaeda63 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java @@ -28,7 +28,6 @@ import java.util.Objects; import com.google.gson.annotations.SerializedName; - /** * Gets or Sets EnumClass */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..16025ba6d5c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -207,5 +206,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..377f2ecf0ee 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -33,12 +33,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -384,5 +383,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..3f3d3cac61c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @SerializedName("bar") private String bar = null; @@ -100,5 +99,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..5337fa33974 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -143,5 +142,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..19bb519f9ac 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -35,12 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -146,5 +145,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..bfc8e3ce46e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java @@ -30,13 +30,12 @@ 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 { +public class Model200Response { @SerializedName("name") private Integer name = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..f2c1858099c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -141,5 +140,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..cb608f13f7d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -30,13 +30,12 @@ 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 { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..cfa453712ce 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java @@ -30,13 +30,12 @@ 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 { +public class Name { @SerializedName("name") private Integer name = null; @@ -147,5 +146,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..29e9a9064a5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..d6ecceeb479 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -236,5 +235,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..6124b404449 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -239,5 +238,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..4a90af87156 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @@ -109,5 +108,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..31b5862bb45 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..5d3fbb6bae6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..f2a409f35c4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -256,5 +255,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 00000000000..0b7b245d166 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import java.io.StringWriter; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + +import com.google.gson.Gson; + +//import com.fasterxml.jackson.databind.*; +//import com.fasterxml.jackson.databind.SerializationFeature.*; + +public class EnumValueTest { + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + + // test serialization + Gson gson = new Gson(); + String json = gson.toJson(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\"}"); + + // test deserialization + EnumTest fromString = gson.fromJson(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } + +} diff --git a/samples/client/petstore/java/retrofit/.travis.yml b/samples/client/petstore/java/retrofit/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/retrofit/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: 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/retrofit/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/Animal.md b/samples/client/petstore/java/retrofit/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/AnimalFarm.md b/samples/client/petstore/java/retrofit/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/ArrayTest.md b/samples/client/petstore/java/retrofit/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/Cat.md b/samples/client/petstore/java/retrofit/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Category.md b/samples/client/petstore/java/retrofit/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/Dog.md b/samples/client/petstore/java/retrofit/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/EnumClass.md b/samples/client/petstore/java/retrofit/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/EnumTest.md b/samples/client/petstore/java/retrofit/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/retrofit/docs/FakeApi.md b/samples/client/petstore/java/retrofit/docs/FakeApi.md new file mode 100644 index 00000000000..21a4db7c377 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/FakeApi.md @@ -0,0 +1,122 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit/docs/FormatTest.md b/samples/client/petstore/java/retrofit/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/retrofit/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/retrofit/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/MapTest.md b/samples/client/petstore/java/retrofit/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/MapTest.md @@ -0,0 +1,17 @@ + +# 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 +---- | ----- + + + diff --git a/samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Model200Response.md b/samples/client/petstore/java/retrofit/docs/Model200Response.md new file mode 100644 index 00000000000..b47618b28cc --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/ModelApiResponse.md b/samples/client/petstore/java/retrofit/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/ModelReturn.md b/samples/client/petstore/java/retrofit/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Name.md b/samples/client/petstore/java/retrofit/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/NumberOnly.md b/samples/client/petstore/java/retrofit/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/Order.md b/samples/client/petstore/java/retrofit/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/retrofit/docs/Pet.md b/samples/client/petstore/java/retrofit/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/PetApi.md b/samples/client/petstore/java/retrofit/docs/PetApi.md new file mode 100644 index 00000000000..e0314e20e51 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> 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 | + +### 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/retrofit/docs/ReadOnlyFirst.md b/samples/client/petstore/java/retrofit/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/SpecialModelName.md b/samples/client/petstore/java/retrofit/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/StoreApi.md b/samples/client/petstore/java/retrofit/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> 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>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit/docs/Tag.md b/samples/client/petstore/java/retrofit/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/User.md b/samples/client/petstore/java/retrofit/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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/retrofit/docs/UserApi.md b/samples/client/petstore/java/retrofit/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> 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/retrofit/gradlew.bat b/samples/client/petstore/java/retrofit/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/retrofit/gradlew.bat +++ b/samples/client/petstore/java/retrofit/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index ee6ce62988f..2944d770af7 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -104,6 +104,11 @@ 1.7
    + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -142,7 +147,7 @@ - 1.5.8 + 1.5.9 1.9.0 2.7.5 2.9.3 diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 0453c60ae01..59094331de2 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -56,6 +56,8 @@ public ApiClient(String[] authNames) { Interceptor auth; if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); } else if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { @@ -404,4 +406,4 @@ public LocalDate read(JsonReader in) throws IOException { return formatter.parseLocalDate(date); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..31140c76df4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/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 99df18ed71f..0f8f3975814 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -6,6 +6,7 @@ import retrofit.http.*; import retrofit.mime.*; +import io.swagger.client.model.Client; import org.joda.time.LocalDate; import org.joda.time.DateTime; import java.math.BigDecimal; @@ -16,29 +17,56 @@ import java.util.Map; public interface FakeApi { + /** + * To test \"client\" model + * Sync method + * + * @param body client model (required) + * @return Client + */ + + @PATCH("/fake") + Client testClientModel( + @retrofit.http.Body Client body + ); + + /** + * To test \"client\" model + * Async method + * @param body client model (required) + * @param cb callback method + * @return void + */ + + @PATCH("/fake") + void testClientModel( + @retrofit.http.Body Client body, Callback cb + ); /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Sync method * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @return Void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + @retrofit.http.Field("number") BigDecimal number, @retrofit.http.Field("double") Double _double, @retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit.http.Field("byte") byte[] _byte, @retrofit.http.Field("integer") Integer integer, @retrofit.http.Field("int32") Integer int32, @retrofit.http.Field("int64") Long int64, @retrofit.http.Field("float") Float _float, @retrofit.http.Field("string") String string, @retrofit.http.Field("binary") byte[] binary, @retrofit.http.Field("date") LocalDate date, @retrofit.http.Field("dateTime") DateTime dateTime, @retrofit.http.Field("password") String password, @retrofit.http.Field("callback") String paramCallback ); /** @@ -46,23 +74,66 @@ Void testEndpointParameters( * Async method * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @param cb callback method * @return void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb + @retrofit.http.Field("number") BigDecimal number, @retrofit.http.Field("double") Double _double, @retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit.http.Field("byte") byte[] _byte, @retrofit.http.Field("integer") Integer integer, @retrofit.http.Field("int32") Integer int32, @retrofit.http.Field("int64") Long int64, @retrofit.http.Field("float") Float _float, @retrofit.http.Field("string") String string, @retrofit.http.Field("binary") byte[] binary, @retrofit.http.Field("date") LocalDate date, @retrofit.http.Field("dateTime") DateTime dateTime, @retrofit.http.Field("password") String password, @retrofit.http.Field("callback") String paramCallback, Callback cb + ); + /** + * To test enum parameters + * Sync method + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return Void + */ + + @retrofit.http.FormUrlEncoded + @GET("/fake") + 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") BigDecimal enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble + ); + + /** + * To test enum parameters + * Async method + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param cb callback method + * @return void + */ + + @retrofit.http.FormUrlEncoded + @GET("/fake") + 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") BigDecimal enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 66ed6aea981..eaaac18845f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -26,7 +26,7 @@ public interface PetApi { @POST("/pet") Void addPet( - @Body Pet body + @retrofit.http.Body Pet body ); /** @@ -39,7 +39,7 @@ Void addPet( @POST("/pet") void addPet( - @Body Pet body, Callback cb + @retrofit.http.Body Pet body, Callback cb ); /** * Deletes a pet @@ -52,7 +52,7 @@ void addPet( @DELETE("/pet/{petId}") Void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + @retrofit.http.Path("petId") Long petId, @retrofit.http.Header("api_key") String apiKey ); /** @@ -66,7 +66,7 @@ Void deletePet( @DELETE("/pet/{petId}") void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb + @retrofit.http.Path("petId") Long petId, @retrofit.http.Header("api_key") String apiKey, Callback cb ); /** * Finds Pets by status @@ -78,7 +78,7 @@ void deletePet( @GET("/pet/findByStatus") List findPetsByStatus( - @Query("status") CSVParams status + @retrofit.http.Query("status") CSVParams status ); /** @@ -91,7 +91,7 @@ List findPetsByStatus( @GET("/pet/findByStatus") void findPetsByStatus( - @Query("status") CSVParams status, Callback> cb + @retrofit.http.Query("status") CSVParams status, Callback> cb ); /** * Finds Pets by tags @@ -103,7 +103,7 @@ void findPetsByStatus( @GET("/pet/findByTags") List findPetsByTags( - @Query("tags") CSVParams tags + @retrofit.http.Query("tags") CSVParams tags ); /** @@ -116,7 +116,7 @@ List findPetsByTags( @GET("/pet/findByTags") void findPetsByTags( - @Query("tags") CSVParams tags, Callback> cb + @retrofit.http.Query("tags") CSVParams tags, Callback> cb ); /** * Find pet by ID @@ -128,7 +128,7 @@ void findPetsByTags( @GET("/pet/{petId}") Pet getPetById( - @Path("petId") Long petId + @retrofit.http.Path("petId") Long petId ); /** @@ -141,7 +141,7 @@ Pet getPetById( @GET("/pet/{petId}") void getPetById( - @Path("petId") Long petId, Callback cb + @retrofit.http.Path("petId") Long petId, Callback cb ); /** * Update an existing pet @@ -153,7 +153,7 @@ void getPetById( @PUT("/pet") Void updatePet( - @Body Pet body + @retrofit.http.Body Pet body ); /** @@ -166,7 +166,7 @@ Void updatePet( @PUT("/pet") void updatePet( - @Body Pet body, Callback cb + @retrofit.http.Body Pet body, Callback cb ); /** * Updates a pet in the store with form data @@ -178,10 +178,10 @@ void updatePet( * @return Void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/pet/{petId}") Void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + @retrofit.http.Path("petId") Long petId, @retrofit.http.Field("name") String name, @retrofit.http.Field("status") String status ); /** @@ -194,10 +194,10 @@ Void updatePetWithForm( * @return void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/pet/{petId}") void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status, Callback cb + @retrofit.http.Path("petId") Long petId, @retrofit.http.Field("name") String name, @retrofit.http.Field("status") String status, Callback cb ); /** * uploads an image @@ -209,10 +209,10 @@ void updatePetWithForm( * @return ModelApiResponse */ - @Multipart + @retrofit.http.Multipart @POST("/pet/{petId}/uploadImage") ModelApiResponse uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file + @retrofit.http.Path("petId") Long petId, @retrofit.http.Part("additionalMetadata") String additionalMetadata, @retrofit.http.Part("file") TypedFile file ); /** @@ -225,9 +225,9 @@ ModelApiResponse uploadFile( * @return void */ - @Multipart + @retrofit.http.Multipart @POST("/pet/{petId}/uploadImage") void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb + @retrofit.http.Path("petId") Long petId, @retrofit.http.Part("additionalMetadata") String additionalMetadata, @retrofit.http.Part("file") TypedFile file, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index def4aa2efc7..c29f87ef9cc 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -24,7 +24,7 @@ public interface StoreApi { @DELETE("/store/order/{orderId}") Void deleteOrder( - @Path("orderId") String orderId + @retrofit.http.Path("orderId") String orderId ); /** @@ -37,7 +37,7 @@ Void deleteOrder( @DELETE("/store/order/{orderId}") void deleteOrder( - @Path("orderId") String orderId, Callback cb + @retrofit.http.Path("orderId") String orderId, Callback cb ); /** * Returns pet inventories by status @@ -71,7 +71,7 @@ void getInventory( @GET("/store/order/{orderId}") Order getOrderById( - @Path("orderId") Long orderId + @retrofit.http.Path("orderId") Long orderId ); /** @@ -84,7 +84,7 @@ Order getOrderById( @GET("/store/order/{orderId}") void getOrderById( - @Path("orderId") Long orderId, Callback cb + @retrofit.http.Path("orderId") Long orderId, Callback cb ); /** * Place an order for a pet @@ -96,7 +96,7 @@ void getOrderById( @POST("/store/order") Order placeOrder( - @Body Order body + @retrofit.http.Body Order body ); /** @@ -109,6 +109,6 @@ Order placeOrder( @POST("/store/order") void placeOrder( - @Body Order body, Callback cb + @retrofit.http.Body Order body, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 8c3380d07d4..43876970c3f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -24,7 +24,7 @@ public interface UserApi { @POST("/user") Void createUser( - @Body User body + @retrofit.http.Body User body ); /** @@ -37,7 +37,7 @@ Void createUser( @POST("/user") void createUser( - @Body User body, Callback cb + @retrofit.http.Body User body, Callback cb ); /** * Creates list of users with given input array @@ -49,7 +49,7 @@ void createUser( @POST("/user/createWithArray") Void createUsersWithArrayInput( - @Body List body + @retrofit.http.Body List body ); /** @@ -62,7 +62,7 @@ Void createUsersWithArrayInput( @POST("/user/createWithArray") void createUsersWithArrayInput( - @Body List body, Callback cb + @retrofit.http.Body List body, Callback cb ); /** * Creates list of users with given input array @@ -74,7 +74,7 @@ void createUsersWithArrayInput( @POST("/user/createWithList") Void createUsersWithListInput( - @Body List body + @retrofit.http.Body List body ); /** @@ -87,7 +87,7 @@ Void createUsersWithListInput( @POST("/user/createWithList") void createUsersWithListInput( - @Body List body, Callback cb + @retrofit.http.Body List body, Callback cb ); /** * Delete user @@ -99,7 +99,7 @@ void createUsersWithListInput( @DELETE("/user/{username}") Void deleteUser( - @Path("username") String username + @retrofit.http.Path("username") String username ); /** @@ -112,7 +112,7 @@ Void deleteUser( @DELETE("/user/{username}") void deleteUser( - @Path("username") String username, Callback cb + @retrofit.http.Path("username") String username, Callback cb ); /** * Get user by user name @@ -124,7 +124,7 @@ void deleteUser( @GET("/user/{username}") User getUserByName( - @Path("username") String username + @retrofit.http.Path("username") String username ); /** @@ -137,7 +137,7 @@ User getUserByName( @GET("/user/{username}") void getUserByName( - @Path("username") String username, Callback cb + @retrofit.http.Path("username") String username, Callback cb ); /** * Logs user into the system @@ -150,7 +150,7 @@ void getUserByName( @GET("/user/login") String loginUser( - @Query("username") String username, @Query("password") String password + @retrofit.http.Query("username") String username, @retrofit.http.Query("password") String password ); /** @@ -164,7 +164,7 @@ String loginUser( @GET("/user/login") void loginUser( - @Query("username") String username, @Query("password") String password, Callback cb + @retrofit.http.Query("username") String username, @retrofit.http.Query("password") String password, Callback cb ); /** * Logs out current logged in user session @@ -199,7 +199,7 @@ void logoutUser( @PUT("/user/{username}") Void updateUser( - @Path("username") String username, @Body User body + @retrofit.http.Path("username") String username, @retrofit.http.Body User body ); /** @@ -213,6 +213,6 @@ Void updateUser( @PUT("/user/{username}") void updateUser( - @Path("username") String username, @Body User body, Callback cb + @retrofit.http.Path("username") String username, @retrofit.http.Body User body, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 59d01238796..2f973bb5e05 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public Response intercept(Chain chain) throws IOException { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..18c25738e0f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ -/** +/* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 839b04aa6c5..81d139e630b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,49 +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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; -import com.google.gson.annotations.SerializedName; - - - +/** + * AdditionalPropertiesClass + */ - -public class AdditionalPropertiesClass { - +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - /** - **/ - @ApiModelProperty(value = "") + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", value = "") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - /** - **/ - @ApiModelProperty(value = "") + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", value = "") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -51,8 +100,8 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); } @Override @@ -75,10 +124,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index 9a14a1289fe..bc73c4f93cb 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -1,46 +1,85 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - +/** + * Animal + */ - - -public class Animal { - +public class Animal { @SerializedName("className") private String className = null; @SerializedName("color") private String color = "red"; - /** - **/ - @ApiModelProperty(required = true, value = "") + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - /** - **/ - @ApiModelProperty(value = "") + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -48,8 +87,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override @@ -72,10 +111,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java index c7d37b1512c..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -5,30 +30,26 @@ import java.util.ArrayList; import java.util.List; -import com.google.gson.annotations.SerializedName; - - - +/** + * AnimalFarm + */ - -public class AnimalFarm extends ArrayList { - +public class AnimalFarm extends ArrayList { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - AnimalFarm animalFarm = (AnimalFarm) o; return true; } @Override public int hashCode() { - return Objects.hash(); + return Objects.hash(super.hashCode()); } @Override @@ -44,10 +65,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..e0dde620ab4 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,107 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..e529ebc4fa8 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,107 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java index 92337cc0246..80df1b341f5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,19 +1,43 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; -import com.google.gson.annotations.SerializedName; - - - - +/** + * ArrayTest + */ -public class ArrayTest { - +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -23,39 +47,78 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - **/ - @ApiModelProperty(value = "") + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", value = "") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - /** - **/ - @ApiModelProperty(value = "") + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", value = "") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - /** - **/ - @ApiModelProperty(value = "") + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", value = "") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -63,9 +126,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override @@ -89,10 +152,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 287d6a4d94c..10a2f2c5c8d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -1,60 +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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import com.google.gson.annotations.SerializedName; - - - - - -public class Cat extends Animal { - - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; +/** + * Cat + */ +public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; } - /** - **/ - @ApiModelProperty(value = "") + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(example = "null", value = "") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -62,14 +67,13 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(className, cat.className) && - Objects.equals(color, cat.color) && - Objects.equals(declawed, cat.declawed); + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -77,8 +81,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); @@ -88,10 +90,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java index 93ec7bd0877..153df9edbfa 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java @@ -1,46 +1,85 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - +/** + * Category + */ - - -public class Category { - +public class Category { @SerializedName("id") private Long id = null; @SerializedName("name") private String name = null; - /** - **/ - @ApiModelProperty(value = "") + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -48,8 +87,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -72,10 +111,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..1eb9e755db3 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,99 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Client + */ + +public class Client { + @SerializedName("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index 5d2ead15f07..079def9ecc6 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -1,60 +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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import com.google.gson.annotations.SerializedName; - - - - - -public class Dog extends Animal { - - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; +/** + * Dog + */ +public class Dog extends Animal { @SerializedName("breed") private String breed = null; - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; + public Dog breed(String breed) { + this.breed = breed; + return this; } - /** - **/ - @ApiModelProperty(value = "") + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(example = "null", value = "") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -62,14 +67,13 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(className, dog.className) && - Objects.equals(color, dog.color) && - Objects.equals(breed, dog.breed); + return Objects.equals(this.breed, dog.breed) && + super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed); + return Objects.hash(breed, super.hashCode()); } @Override @@ -77,8 +81,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); @@ -88,10 +90,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..7eea2d2a911 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,173 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName(">=") + GREATER_THAN_OR_EQUAL_TO(">="), + + @SerializedName("$") + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + @SerializedName("fish") + FISH("fish"), + + @SerializedName("crab") + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java index 8f9357fbd32..a6072c381c4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,50 +1,57 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; - import com.google.gson.annotations.SerializedName; - - - -public class EnumClass { +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + @SerializedName("_abc") + _ABC("_abc"), + @SerializedName("-efg") + _EFG("-efg"), + + @SerializedName("(xyz)") + _XYZ_("(xyz)"); - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumClass enumClass = (EnumClass) o; - return true; - } + private String value; - @Override - public int hashCode() { - return Objects.hash(); + EnumClass(String value) { + this.value = value; } @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumClass {\n"); - - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); + return String.valueOf(value); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index 8db392afccc..bdd3a40bb28 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,25 +1,47 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - - - -public class EnumTest { - +/** + * EnumTest + */ +public class EnumTest { /** * Gets or Sets enumString */ public enum EnumStringEnum { @SerializedName("UPPER") UPPER("UPPER"), - + @SerializedName("lower") LOWER("lower"); @@ -38,14 +60,13 @@ public String toString() { @SerializedName("enum_string") private EnumStringEnum enumString = null; - /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { @SerializedName("1") NUMBER_1(1), - + @SerializedName("-1") NUMBER_MINUS_1(-1); @@ -64,14 +85,13 @@ public String toString() { @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; - /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { @SerializedName("1.1") NUMBER_1_DOT_1(1.1), - + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); @@ -90,39 +110,63 @@ public String toString() { @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; - /** - **/ - @ApiModelProperty(value = "") + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", value = "") public EnumStringEnum getEnumString() { return enumString; } + public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } - /** - **/ - @ApiModelProperty(value = "") + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(example = "null", value = "") public EnumIntegerEnum getEnumInteger() { return enumInteger; } + public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } - /** - **/ - @ApiModelProperty(value = "") + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(example = "null", value = "") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -130,9 +174,9 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber); } @Override @@ -156,10 +200,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index 6063cf33f77..023042b8d96 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,20 +1,43 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import org.joda.time.DateTime; import org.joda.time.LocalDate; -import com.google.gson.annotations.SerializedName; - +/** + * FormatTest + */ - - - -public class FormatTest { - +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -54,149 +77,253 @@ public class FormatTest { @SerializedName("password") private String password = null; - /** + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer * minimum: 10.0 * maximum: 100.0 - **/ - @ApiModelProperty(value = "") + * @return integer + **/ + @ApiModelProperty(example = "null", 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.0 * maximum: 200.0 - **/ - @ApiModelProperty(value = "") + * @return int32 + **/ + @ApiModelProperty(example = "null", value = "") public Integer getInt32() { return int32; } + public void setInt32(Integer int32) { this.int32 = int32; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(example = "null", 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 - **/ - @ApiModelProperty(required = true, value = "") + * @return number + **/ + @ApiModelProperty(example = "null", 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 - **/ - @ApiModelProperty(value = "") + * @return _float + **/ + @ApiModelProperty(example = "null", 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 - **/ - @ApiModelProperty(value = "") + * @return _double + **/ + @ApiModelProperty(example = "null", value = "") public Double getDouble() { return _double; } + public void setDouble(Double _double) { this._double = _double; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(example = "null", value = "") public String getString() { return string; } + public void setString(String string) { this.string = string; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(example = "null", required = true, value = "") public byte[] getByte() { return _byte; } + public void setByte(byte[] _byte) { this._byte = _byte; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(example = "null", value = "") public byte[] getBinary() { return binary; } + public void setBinary(byte[] binary) { this.binary = binary; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(example = "null", required = true, value = "") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", required = true, value = "") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -204,19 +331,19 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password); + 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 @@ -250,10 +377,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..43a5b6a6c92 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..75586c606c9 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,157 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", 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) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index cf7f73c705f..e6b8987656a 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,6 +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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -9,14 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; -import com.google.gson.annotations.SerializedName; - - - +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ - -public class MixedPropertiesAndAdditionalPropertiesClass { - +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -26,39 +49,68 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("map") private Map map = new HashMap(); - /** - **/ - @ApiModelProperty(value = "") + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - /** - **/ - @ApiModelProperty(value = "") + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - /** - **/ - @ApiModelProperty(value = "") + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", value = "") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -66,9 +118,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override @@ -92,10 +144,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java index 22d2bbd763d..eabc63cd389 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,49 +1,86 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - - /** * Model for testing model name starting with number - **/ + */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { - + +public class Model200Response { @SerializedName("name") private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; - /** - **/ - @ApiModelProperty(value = "") + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - /** - **/ - @ApiModelProperty(value = "") + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -51,13 +88,13 @@ public boolean equals(Object o) { return false; } Model200Response _200Response = (Model200Response) o; - return Objects.equals(name, _200Response.name) && - Objects.equals(PropertyClass, _200Response.PropertyClass); + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -66,7 +103,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } @@ -75,10 +112,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java index bb5313b42d4..e410a24757f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,17 +1,40 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * ModelApiResponse + */ - -public class ModelApiResponse { - +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -21,39 +44,63 @@ public class ModelApiResponse { @SerializedName("message") private String message = null; - /** - **/ - @ApiModelProperty(value = "") + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(example = "null", value = "") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ - @ApiModelProperty(value = "") + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(example = "null", value = "") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ - @ApiModelProperty(value = "") + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(example = "null", value = "") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -61,9 +108,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -87,10 +134,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java index a3ecfb92156..01d69fecb68 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,36 +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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - - /** * Model for testing reserved words - **/ + */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { - + +public class ModelReturn { @SerializedName("return") private Integer _return = null; - /** - **/ - @ApiModelProperty(value = "") + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(example = "null", value = "") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -38,7 +67,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override @@ -60,10 +89,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java index 5aa60a1f6f1..c50f477abc3 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -1,20 +1,41 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - - /** * Model for testing model name same as property name - **/ + */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { - + +public class Name { @SerializedName("name") private Integer name = null; @@ -27,43 +48,63 @@ public class Name { @SerializedName("123Number") private Integer _123Number = null; - /** - **/ - @ApiModelProperty(required = true, value = "") + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", required = true, value = "") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - /** - **/ - @ApiModelProperty(value = "") + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") public Integer getSnakeCase() { return snakeCase; } - /** - **/ - @ApiModelProperty(value = "") + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - /** - **/ - @ApiModelProperty(value = "") + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", value = "") public Integer get123Number() { return _123Number; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -71,10 +112,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123Number, name._123Number); + 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 @@ -99,10 +140,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..0653baec68b --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,100 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + +/** + * NumberOnly + */ + +public class NumberOnly { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", 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/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index 569d1c0fe46..d15cca81e05 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -1,18 +1,41 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; -import com.google.gson.annotations.SerializedName; - - +/** + * Order + */ - - -public class Order { - +public class Order { @SerializedName("id") private Long id = null; @@ -25,17 +48,16 @@ public class Order { @SerializedName("shipDate") private DateTime shipDate = null; - /** * Order Status */ public enum StatusEnum { @SerializedName("placed") PLACED("placed"), - + @SerializedName("approved") APPROVED("approved"), - + @SerializedName("delivered") DELIVERED("delivered"); @@ -57,70 +79,117 @@ public String toString() { @SerializedName("complete") private Boolean complete = false; - /** - **/ - @ApiModelProperty(value = "") + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(example = "null", value = "") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ - @ApiModelProperty(value = "") + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(example = "null", value = "") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ - @ApiModelProperty(value = "") + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(example = "null", value = "") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - /** + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** * Order Status - **/ - @ApiModelProperty(value = "Order Status") + * @return status + **/ + @ApiModelProperty(example = "null", value = "Order Status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ - @ApiModelProperty(value = "") + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(example = "null", value = "") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -128,12 +197,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -160,10 +229,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index 8efc46bc471..2363e9ed02e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -1,6 +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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -8,14 +34,11 @@ import java.util.ArrayList; import java.util.List; -import com.google.gson.annotations.SerializedName; - - - +/** + * Pet + */ - -public class Pet { - +public class Pet { @SerializedName("id") private Long id = null; @@ -31,17 +54,16 @@ public class Pet { @SerializedName("tags") private List tags = new ArrayList(); - /** * pet status in the store */ public enum StatusEnum { @SerializedName("available") AVAILABLE("available"), - + @SerializedName("pending") PENDING("pending"), - + @SerializedName("sold") SOLD("sold"); @@ -60,70 +82,127 @@ public String toString() { @SerializedName("status") private StatusEnum status = null; - /** - **/ - @ApiModelProperty(value = "") + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(example = "null", value = "") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ - @ApiModelProperty(required = true, value = "") + 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; } - /** - **/ - @ApiModelProperty(required = true, value = "") + 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(example = "null", required = true, value = "") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ - @ApiModelProperty(value = "") + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", 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 - **/ - @ApiModelProperty(value = "pet status in the store") + * @return status + **/ + @ApiModelProperty(example = "null", value = "pet status in the store") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -131,12 +210,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -163,10 +242,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 32e4f515bce..f9f1503366f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,43 +1,76 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - +/** + * ReadOnlyFirst + */ - - - -public class ReadOnlyFirst { - +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @SerializedName("baz") private String baz = null; - /** - **/ - @ApiModelProperty(value = "") + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") public String getBar() { return bar; } - /** - **/ - @ApiModelProperty(value = "") + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", value = "") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -45,8 +78,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override @@ -69,10 +102,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java index e2354b064b2..10d56096dea 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,33 +1,64 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - - +/** + * SpecialModelName + */ -public class SpecialModelName { - +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; - /** - **/ - @ApiModelProperty(value = "") + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(example = "null", value = "") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -35,7 +66,7 @@ public boolean equals(Object o) { return false; } SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(specialPropertyName, specialModelName.specialPropertyName); + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); } @Override @@ -57,10 +88,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java index 9c5ac6cf9a7..11870f0f0a8 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java @@ -1,46 +1,85 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - +/** + * Tag + */ - - -public class Tag { - +public class Tag { @SerializedName("id") private Long id = null; @SerializedName("name") private String name = null; - /** - **/ - @ApiModelProperty(value = "") + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -48,8 +87,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -72,10 +111,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + 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/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java index 39e40837a6a..b04dc861682 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java @@ -1,17 +1,40 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * User + */ - -public class User { - +public class User { @SerializedName("id") private Long id = null; @@ -36,90 +59,153 @@ public class User { @SerializedName("userStatus") private Integer userStatus = null; - /** - **/ - @ApiModelProperty(value = "") + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(example = "null", value = "") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ - @ApiModelProperty(value = "") + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(example = "null", value = "") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ - @ApiModelProperty(value = "") + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(example = "null", value = "") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ - @ApiModelProperty(value = "") + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(example = "null", value = "") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ - @ApiModelProperty(value = "") + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", value = "") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ - @ApiModelProperty(value = "") + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(example = "null", 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 - **/ - @ApiModelProperty(value = "User Status") + * @return userStatus + **/ + @ApiModelProperty(example = "null", value = "User Status") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -127,14 +213,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -163,10 +249,12 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } + } + diff --git a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/retrofit2/docs/Cat.md b/samples/client/petstore/java/retrofit2/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/retrofit2/docs/Cat.md +++ b/samples/client/petstore/java/retrofit2/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/Client.md b/samples/client/petstore/java/retrofit2/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/Dog.md b/samples/client/petstore/java/retrofit2/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/retrofit2/docs/Dog.md +++ b/samples/client/petstore/java/retrofit2/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/EnumArrays.md b/samples/client/petstore/java/retrofit2/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/EnumArrays.md @@ -0,0 +1,27 @@ + +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] +**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] + + + +## Enum: JustSymbolEnum +Name | Value +---- | ----- +GREATER_THAN_OR_EQUAL_TO | ">=" +DOLLAR | "$" + + + +## Enum: List<ArrayEnumEnum> +Name | Value +---- | ----- +FISH | "fish" +CRAB | "crab" + + + diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index 0e646d63479..2e2b792d8d3 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** fake | To test code injection =end +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters - -# **testCodeInjectEnd** -> Void testCodeInjectEnd(testCodeInjectEnd) + +# **testClientModel** +> Client testClientModel(body) -To test code injection =end +To test \"client\" model ### Example ```java @@ -23,12 +23,12 @@ To test code injection =end FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end +Client body = new Client(); // Client | client model try { - Void result = apiInstance.testCodeInjectEnd(testCodeInjectEnd); + Client result = apiInstance.testClientModel(body); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); + System.err.println("Exception when calling FakeApi#testClientModel"); e.printStackTrace(); } ``` @@ -37,11 +37,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -[**Void**](.md) +[**Client**](Client.md) ### Authorization @@ -49,12 +49,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json # **testEndpointParameters** -> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,36 @@ 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 string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); @@ -95,16 +106,18 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| 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** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type @@ -112,18 +125,18 @@ Name | Type | Description | Notes ### Authorization -No authorization required +[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 - -# **testEnumQueryParameters** -> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> Void testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -133,14 +146,19 @@ To test enum query parameters 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) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -149,6 +167,11 @@ try { 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** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/MapTest.md b/samples/client/petstore/java/retrofit2/docs/MapTest.md index c671e97ffbc..714a97a40d9 100644 --- a/samples/client/petstore/java/retrofit2/docs/MapTest.md +++ b/samples/client/petstore/java/retrofit2/docs/MapTest.md @@ -12,6 +12,8 @@ Name | Type | Description | Notes ## Enum: Map<String, InnerEnum> Name | Value ---- | ----- +UPPER | "UPPER" +LOWER | "lower" diff --git a/samples/client/petstore/java/retrofit2/docs/Model200Response.md b/samples/client/petstore/java/retrofit2/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/retrofit2/docs/Model200Response.md +++ b/samples/client/petstore/java/retrofit2/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/PetApi.md b/samples/client/petstore/java/retrofit2/docs/PetApi.md index 40ea199b153..211f5be5fa8 100644 --- a/samples/client/petstore/java/retrofit2/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2/docs/PetApi.md @@ -160,7 +160,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] ### Return type diff --git a/samples/client/petstore/java/retrofit2/gradlew.bat b/samples/client/petstore/java/retrofit2/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/retrofit2/gradlew.bat +++ b/samples/client/petstore/java/retrofit2/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 3af9daa695e..247b281c33b 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -95,6 +96,11 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -138,6 +144,7 @@ + UTF-8 1.7 ${java.version} ${java.version} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index ffb4c11be1d..be9eadc33ba 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -53,10 +53,12 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -66,7 +68,7 @@ public ApiClient(String[] authNames) { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -74,8 +76,8 @@ public ApiClient(String authName) { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -84,9 +86,9 @@ public ApiClient(String authName, String apiKey) { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -95,11 +97,11 @@ public ApiClient(String authName, String username, String password) { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client Secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -141,7 +143,7 @@ public S createService(Class serviceClass) { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -155,8 +157,8 @@ private void setApiKey(String apiKey) { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -175,7 +177,7 @@ private void setCredentials(String username, String password) { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -189,7 +191,7 @@ public TokenRequestBuilder getTokenEndPoint() { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -203,7 +205,7 @@ public AuthenticationRequestBuilder getAuthorizationEndPoint() { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -217,9 +219,9 @@ public void setAccessToken(String accessToken) { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -239,7 +241,7 @@ public void configureAuthorizationFlow(String clientId, String clientSecret, Str /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -253,8 +255,8 @@ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization interceptor */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -292,7 +294,7 @@ public void addAuthsToOkBuilder(OkHttpClient.Builder okBuilder) { /** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit - * @param okClient + * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/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 004ba1916a5..d1068513f0e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,9 +8,10 @@ import okhttp3.RequestBody; +import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -19,16 +20,15 @@ public interface FakeApi { /** - * To test code injection =end + * To test \"client\" model * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return Call + * @param body client model (required) + * @return Call<Client> */ - @FormUrlEncoded - @PUT("fake") - Call testCodeInjectEnd( - @Field("test code inject */ =end") String testCodeInjectEnd + @PATCH("fake") + Call testClientModel( + @retrofit2.http.Body Client body ); /** @@ -36,38 +36,45 @@ Call testCodeInjectEnd( * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call + * @param paramCallback None (optional) + * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + @retrofit2.http.Field("number") BigDecimal number, @retrofit2.http.Field("double") Double _double, @retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit2.http.Field("byte") byte[] _byte, @retrofit2.http.Field("integer") Integer integer, @retrofit2.http.Field("int32") Integer int32, @retrofit2.http.Field("int64") Long int64, @retrofit2.http.Field("float") Float _float, @retrofit2.http.Field("string") String string, @retrofit2.http.Field("binary") byte[] binary, @retrofit2.http.Field("date") LocalDate date, @retrofit2.http.Field("dateTime") DateTime dateTime, @retrofit2.http.Field("password") String password, @retrofit2.http.Field("callback") String paramCallback ); /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call + * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @GET("fake") - Call testEnumQueryParameters( - @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + Call testEnumParameters( + @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") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index ec9d67a7449..3f61279a66b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; @@ -22,12 +22,12 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call<Void> */ @POST("pet") Call addPet( - @Body Pet body + @retrofit2.http.Body Pet body ); /** @@ -35,60 +35,60 @@ Call addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call + * @return Call<Void> */ @DELETE("pet/{petId}") Call deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Header("api_key") String apiKey ); /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter (required) - * @return Call> + * @return Call<List> */ @GET("pet/findByStatus") Call> findPetsByStatus( - @Query("status") CSVParams status + @retrofit2.http.Query("status") CSVParams status ); /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by (required) - * @return Call> + * @return Call<List> */ @GET("pet/findByTags") Call> findPetsByTags( - @Query("tags") CSVParams tags + @retrofit2.http.Query("tags") CSVParams tags ); /** * Find pet by ID * Returns a single pet * @param petId ID of pet to return (required) - * @return Call + * @return Call<Pet> */ @GET("pet/{petId}") Call getPetById( - @Path("petId") Long petId + @retrofit2.http.Path("petId") Long petId ); /** * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call<Void> */ @PUT("pet") Call updatePet( - @Body Pet body + @retrofit2.http.Body Pet body ); /** @@ -97,13 +97,13 @@ Call updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call + * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("pet/{petId}") Call updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Field("name") String name, @retrofit2.http.Field("status") String status ); /** @@ -112,13 +112,13 @@ Call updatePetWithForm( * @param petId ID of pet to update (required) * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) - * @return Call + * @return Call<ModelApiResponse> */ - @Multipart + @retrofit2.http.Multipart @POST("pet/{petId}/uploadImage") Call uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("additionalMetadata") String additionalMetadata, @retrofit2.http.Part("file\"; filename=\"file") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 1651c07482c..f9df7d8e8d6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,18 +20,18 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call + * @return Call<Void> */ @DELETE("store/order/{orderId}") Call deleteOrder( - @Path("orderId") String orderId + @retrofit2.http.Path("orderId") String orderId ); /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call> + * @return Call<Map> */ @GET("store/inventory") @@ -42,24 +42,24 @@ Call deleteOrder( * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched (required) - * @return Call + * @return Call<Order> */ @GET("store/order/{orderId}") Call getOrderById( - @Path("orderId") Long orderId + @retrofit2.http.Path("orderId") Long orderId ); /** * Place an order for a pet * * @param body order placed for purchasing the pet (required) - * @return Call + * @return Call<Order> */ @POST("store/order") Call placeOrder( - @Body Order body + @retrofit2.http.Body Order body ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index a0f17545a0f..ee1114dc2dc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -20,60 +20,60 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call + * @return Call<Void> */ @POST("user") Call createUser( - @Body User body + @retrofit2.http.Body User body ); /** * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call<Void> */ @POST("user/createWithArray") Call createUsersWithArrayInput( - @Body List body + @retrofit2.http.Body List body ); /** * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call<Void> */ @POST("user/createWithList") Call createUsersWithListInput( - @Body List body + @retrofit2.http.Body List body ); /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call + * @return Call<Void> */ @DELETE("user/{username}") Call deleteUser( - @Path("username") String username + @retrofit2.http.Path("username") String username ); /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return Call + * @return Call<User> */ @GET("user/{username}") Call getUserByName( - @Path("username") String username + @retrofit2.http.Path("username") String username ); /** @@ -81,18 +81,18 @@ Call getUserByName( * * @param username The user name for login (required) * @param password The password for login in clear text (required) - * @return Call + * @return Call<String> */ @GET("user/login") Call loginUser( - @Query("username") String username, @Query("password") String password + @retrofit2.http.Query("username") String username, @retrofit2.http.Query("password") String password ); /** * Logs out current logged in user session * - * @return Call + * @return Call<Void> */ @GET("user/logout") @@ -104,12 +104,12 @@ Call loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call + * @return Call<Void> */ @PUT("user/{username}") Call updateUser( - @Path("username") String username, @Body User body + @retrofit2.http.Path("username") String username, @retrofit2.http.Body User body ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index f210c2110b5..05bf9561fe3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.url().uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public Response intercept(Chain chain) throws IOException { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..81d139e630b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -50,6 +49,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +72,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty @@ -121,5 +130,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..bc73c4f93cb 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @SerializedName("className") private String className = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..e0dde620ab4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -47,6 +46,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber @@ -98,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..e529ebc4fa8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -47,6 +46,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber @@ -98,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..80df1b341f5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -48,36 +47,16 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -96,6 +75,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -114,6 +98,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel @@ -127,24 +116,6 @@ public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +128,12 @@ public boolean equals(java.lang.Object o) { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +144,6 @@ public String toString() { 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(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } @@ -189,5 +158,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..10a2f2c5c8d 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,57 +31,14 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - +public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +67,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +81,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); @@ -143,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..153df9edbfa 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..1eb9e755db3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,99 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Client + */ + +public class Client { + @SerializedName("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(example = "null", value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..079def9ecc6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,57 +31,14 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - +public class Dog extends Animal { @SerializedName("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +67,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +81,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); @@ -143,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..7eea2d2a911 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,173 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName(">=") + GREATER_THAN_OR_EQUAL_TO(">="), + + @SerializedName("$") + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + @SerializedName("fish") + FISH("fish"), + + @SerializedName("crab") + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..a6072c381c4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..bdd3a40bb28 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -207,5 +206,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..023042b8d96 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -384,5 +383,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..43a5b6a6c92 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @SerializedName("bar") private String bar = null; @@ -100,5 +99,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..75586c606c9 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -72,6 +71,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -90,6 +94,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString @@ -143,5 +152,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..e6b8987656a 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -35,12 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -91,6 +90,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map @@ -146,5 +150,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..eabc63cd389 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,18 +30,17 @@ 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 { +public class Model200Response { @SerializedName("name") private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -61,22 +60,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -90,12 +89,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -104,7 +103,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..e410a24757f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -141,5 +140,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..01d69fecb68 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,13 +30,12 @@ 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 { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..c50f477abc3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,13 +30,12 @@ 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 { +public class Name { @SerializedName("name") private Integer name = null; @@ -147,5 +146,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..0653baec68b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..d15cca81e05 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -236,5 +235,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..2363e9ed02e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -142,6 +141,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +164,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags @@ -239,5 +248,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..f9f1503366f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @@ -109,5 +108,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..10d56096dea 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..11870f0f0a8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..b04dc861682 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -256,5 +255,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/retrofit2rx/docs/Cat.md b/samples/client/petstore/java/retrofit2rx/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Cat.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/Client.md b/samples/client/petstore/java/retrofit2rx/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/Dog.md b/samples/client/petstore/java/retrofit2rx/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Dog.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/EnumArrays.md b/samples/client/petstore/java/retrofit2rx/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/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/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index 0e646d63479..2e2b792d8d3 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** fake | To test code injection =end +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters - -# **testCodeInjectEnd** -> Void testCodeInjectEnd(testCodeInjectEnd) + +# **testClientModel** +> Client testClientModel(body) -To test code injection =end +To test \"client\" model ### Example ```java @@ -23,12 +23,12 @@ To test code injection =end FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end +Client body = new Client(); // Client | client model try { - Void result = apiInstance.testCodeInjectEnd(testCodeInjectEnd); + Client result = apiInstance.testClientModel(body); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); + System.err.println("Exception when calling FakeApi#testClientModel"); e.printStackTrace(); } ``` @@ -37,11 +37,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -[**Void**](.md) +[**Client**](Client.md) ### Authorization @@ -49,12 +49,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json # **testEndpointParameters** -> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,36 @@ 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 string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); @@ -95,16 +106,18 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| 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** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type @@ -112,18 +125,18 @@ Name | Type | Description | Notes ### Authorization -No authorization required +[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 - -# **testEnumQueryParameters** -> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> Void testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -133,14 +146,19 @@ To test enum query parameters 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) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -149,6 +167,11 @@ try { 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** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/MapTest.md b/samples/client/petstore/java/retrofit2rx/docs/MapTest.md index c671e97ffbc..714a97a40d9 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/MapTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/MapTest.md @@ -12,6 +12,8 @@ Name | Type | Description | Notes ## Enum: Map<String, InnerEnum> Name | Value ---- | ----- +UPPER | "UPPER" +LOWER | "lower" diff --git a/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md b/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md index 40ea199b153..211f5be5fa8 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md @@ -160,7 +160,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] ### Return type diff --git a/samples/client/petstore/java/retrofit2rx/gradlew.bat b/samples/client/petstore/java/retrofit2rx/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/retrofit2rx/gradlew.bat +++ b/samples/client/petstore/java/retrofit2rx/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index a56d38dc759..ccc4b12d82b 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -95,6 +96,11 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + @@ -148,6 +154,7 @@ + UTF-8 1.7 ${java.version} ${java.version} 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 ea73efea029..cc82b88c425 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 @@ -53,10 +53,12 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -66,7 +68,7 @@ public ApiClient(String[] authNames) { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -74,8 +76,8 @@ public ApiClient(String authName) { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -84,9 +86,9 @@ public ApiClient(String authName, String apiKey) { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -95,11 +97,11 @@ public ApiClient(String authName, String username, String password) { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client Secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -141,7 +143,7 @@ public S createService(Class serviceClass) { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -155,8 +157,8 @@ private void setApiKey(String apiKey) { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -175,7 +177,7 @@ private void setCredentials(String username, String password) { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -189,7 +191,7 @@ public TokenRequestBuilder getTokenEndPoint() { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -203,7 +205,7 @@ public AuthenticationRequestBuilder getAuthorizationEndPoint() { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -217,9 +219,9 @@ public void setAccessToken(String accessToken) { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -239,7 +241,7 @@ public void configureAuthorizationFlow(String clientId, String clientSecret, Str /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -253,8 +255,8 @@ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization interceptor */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -292,7 +294,7 @@ public void addAuthsToOkBuilder(OkHttpClient.Builder okBuilder) { /** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit - * @param okClient + * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/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 fd700761fac..2b832afd1ef 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,9 +8,10 @@ import okhttp3.RequestBody; +import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -19,16 +20,15 @@ public interface FakeApi { /** - * To test code injection =end + * To test \"client\" model * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return Call + * @param body client model (required) + * @return Call<Client> */ - @FormUrlEncoded - @PUT("fake") - Observable testCodeInjectEnd( - @Field("test code inject */ =end") String testCodeInjectEnd + @PATCH("fake") + Observable testClientModel( + @retrofit2.http.Body Client body ); /** @@ -36,38 +36,45 @@ Observable testCodeInjectEnd( * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call + * @param paramCallback None (optional) + * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("fake") Observable testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + @retrofit2.http.Field("number") BigDecimal number, @retrofit2.http.Field("double") Double _double, @retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit2.http.Field("byte") byte[] _byte, @retrofit2.http.Field("integer") Integer integer, @retrofit2.http.Field("int32") Integer int32, @retrofit2.http.Field("int64") Long int64, @retrofit2.http.Field("float") Float _float, @retrofit2.http.Field("string") String string, @retrofit2.http.Field("binary") byte[] binary, @retrofit2.http.Field("date") LocalDate date, @retrofit2.http.Field("dateTime") DateTime dateTime, @retrofit2.http.Field("password") String password, @retrofit2.http.Field("callback") String paramCallback ); /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call + * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @GET("fake") - Observable testEnumQueryParameters( - @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + Observable testEnumParameters( + @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") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 4a2e64b726e..3c183bb08f9 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; @@ -22,12 +22,12 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call<Void> */ @POST("pet") Observable addPet( - @Body Pet body + @retrofit2.http.Body Pet body ); /** @@ -35,60 +35,60 @@ Observable addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call + * @return Call<Void> */ @DELETE("pet/{petId}") Observable deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Header("api_key") String apiKey ); /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter (required) - * @return Call> + * @return Call<List> */ @GET("pet/findByStatus") Observable> findPetsByStatus( - @Query("status") CSVParams status + @retrofit2.http.Query("status") CSVParams status ); /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by (required) - * @return Call> + * @return Call<List> */ @GET("pet/findByTags") Observable> findPetsByTags( - @Query("tags") CSVParams tags + @retrofit2.http.Query("tags") CSVParams tags ); /** * Find pet by ID * Returns a single pet * @param petId ID of pet to return (required) - * @return Call + * @return Call<Pet> */ @GET("pet/{petId}") Observable getPetById( - @Path("petId") Long petId + @retrofit2.http.Path("petId") Long petId ); /** * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call<Void> */ @PUT("pet") Observable updatePet( - @Body Pet body + @retrofit2.http.Body Pet body ); /** @@ -97,13 +97,13 @@ Observable updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call + * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("pet/{petId}") Observable updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Field("name") String name, @retrofit2.http.Field("status") String status ); /** @@ -112,13 +112,13 @@ Observable updatePetWithForm( * @param petId ID of pet to update (required) * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) - * @return Call + * @return Call<ModelApiResponse> */ - @Multipart + @retrofit2.http.Multipart @POST("pet/{petId}/uploadImage") Observable uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("additionalMetadata") String additionalMetadata, @retrofit2.http.Part("file\"; filename=\"file") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index 19be150428b..e8eac3c525b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,18 +20,18 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call + * @return Call<Void> */ @DELETE("store/order/{orderId}") Observable deleteOrder( - @Path("orderId") String orderId + @retrofit2.http.Path("orderId") String orderId ); /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call> + * @return Call<Map> */ @GET("store/inventory") @@ -42,24 +42,24 @@ Observable deleteOrder( * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched (required) - * @return Call + * @return Call<Order> */ @GET("store/order/{orderId}") Observable getOrderById( - @Path("orderId") Long orderId + @retrofit2.http.Path("orderId") Long orderId ); /** * Place an order for a pet * * @param body order placed for purchasing the pet (required) - * @return Call + * @return Call<Order> */ @POST("store/order") Observable placeOrder( - @Body Order body + @retrofit2.http.Body Order body ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java index 4cad0d804d7..579134971f8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -20,60 +20,60 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call + * @return Call<Void> */ @POST("user") Observable createUser( - @Body User body + @retrofit2.http.Body User body ); /** * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call<Void> */ @POST("user/createWithArray") Observable createUsersWithArrayInput( - @Body List body + @retrofit2.http.Body List body ); /** * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call<Void> */ @POST("user/createWithList") Observable createUsersWithListInput( - @Body List body + @retrofit2.http.Body List body ); /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call + * @return Call<Void> */ @DELETE("user/{username}") Observable deleteUser( - @Path("username") String username + @retrofit2.http.Path("username") String username ); /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return Call + * @return Call<User> */ @GET("user/{username}") Observable getUserByName( - @Path("username") String username + @retrofit2.http.Path("username") String username ); /** @@ -81,18 +81,18 @@ Observable getUserByName( * * @param username The user name for login (required) * @param password The password for login in clear text (required) - * @return Call + * @return Call<String> */ @GET("user/login") Observable loginUser( - @Query("username") String username, @Query("password") String password + @retrofit2.http.Query("username") String username, @retrofit2.http.Query("password") String password ); /** * Logs out current logged in user session * - * @return Call + * @return Call<Void> */ @GET("user/logout") @@ -104,12 +104,12 @@ Observable loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call + * @return Call<Void> */ @PUT("user/{username}") Observable updateUser( - @Path("username") String username, @Body User body + @retrofit2.http.Path("username") String username, @retrofit2.http.Body User body ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index f210c2110b5..05bf9561fe3 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.url().uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public Response intercept(Chain chain) throws IOException { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..81d139e630b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -50,6 +49,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +72,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty @@ -121,5 +130,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..bc73c4f93cb 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @SerializedName("className") private String className = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..e0dde620ab4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -47,6 +46,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber @@ -98,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..e529ebc4fa8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -47,6 +46,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber @@ -98,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..80df1b341f5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -48,36 +47,16 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -96,6 +75,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -114,6 +98,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel @@ -127,24 +116,6 @@ public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +128,12 @@ public boolean equals(java.lang.Object o) { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +144,6 @@ public String toString() { 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(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } @@ -189,5 +158,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..10a2f2c5c8d 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,57 +31,14 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - +public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +67,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +81,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); @@ -143,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..153df9edbfa 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..1eb9e755db3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,99 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Client + */ + +public class Client { + @SerializedName("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(example = "null", 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/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..079def9ecc6 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,57 +31,14 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - +public class Dog extends Animal { @SerializedName("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +67,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +81,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); @@ -143,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..7eea2d2a911 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,173 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +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 { + @SerializedName(">=") + GREATER_THAN_OR_EQUAL_TO(">="), + + @SerializedName("$") + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + @SerializedName("fish") + FISH("fish"), + + @SerializedName("crab") + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", 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) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", 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/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..a6072c381c4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..bdd3a40bb28 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -207,5 +206,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..023042b8d96 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -384,5 +383,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..43a5b6a6c92 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @SerializedName("bar") private String bar = null; @@ -100,5 +99,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..75586c606c9 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -72,6 +71,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -90,6 +94,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString @@ -143,5 +152,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..e6b8987656a 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -35,12 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -91,6 +90,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map @@ -146,5 +150,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..eabc63cd389 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,18 +30,17 @@ 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 { +public class Model200Response { @SerializedName("name") private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -61,22 +60,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -90,12 +89,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -104,7 +103,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..e410a24757f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -141,5 +140,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..01d69fecb68 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,13 +30,12 @@ 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 { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..c50f477abc3 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,13 +30,12 @@ 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 { +public class Name { @SerializedName("name") private Integer name = null; @@ -147,5 +146,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..0653baec68b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..d15cca81e05 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -236,5 +235,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..2363e9ed02e 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -142,6 +141,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +164,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags @@ -239,5 +248,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..f9f1503366f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @@ -109,5 +108,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..10d56096dea 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..11870f0f0a8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..b04dc861682 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -256,5 +255,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js b/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js index 39a22ebcdbe..06561bb4ab5 100644 --- a/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js +++ b/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js @@ -3,9 +3,8 @@ * Do not edit this file by hand or your changes will be lost next time it is * generated. * - * 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 is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * Version: 1.0.0 - * Generated at: 2016-04-28T06:15:51.482Z * Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen */ /** @@ -46,13 +45,13 @@ API.Client.PetApi = function($http, $httpParamSerializer, $injector) { API.Client.PetApi.$inject = ['$http', '$httpParamSerializer', '$injector']; /** - * Update an existing pet + * Add a new pet to the store * * @param {!Pet} body Pet object that needs to be added to the store * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.addPet = function(body, opt_extraHttpRequestParams) { /** @const {string} */ var path = this.basePath_ + '/pet'; @@ -63,17 +62,15 @@ API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParam var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'body' is set if (!body) { - throw new Error('Missing required parameter body when calling updatePet'); + throw new Error('Missing required parameter body when calling addPet'); } /** @type {!Object} */ var httpRequestParams = { - method: 'PUT', + method: 'POST', url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -85,34 +82,35 @@ API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParam } /** - * Add a new pet to the store + * Deletes a pet * - * @param {!Pet} body Pet object that needs to be added to the store + * @param {!number} petId Pet id to delete + * @param {!string=} opt_apiKey * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.addPet = function(body, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/pet'; + var path = this.basePath_ + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'body' is set - if (!body) { - throw new Error('Missing required parameter body when calling addPet'); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); } + headerParams['api_key'] = opt_apiKey; + /** @type {!Object} */ var httpRequestParams = { - method: 'POST', + method: 'DELETE', url: path, json: true, - data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -152,9 +150,7 @@ API.Client.PetApi.prototype.findPetsByStatus = function(status, opt_extraHttpReq method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -194,9 +190,7 @@ API.Client.PetApi.prototype.findPetsByTags = function(tags, opt_extraHttpRequest method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -233,9 +227,7 @@ API.Client.PetApi.prototype.getPetById = function(petId, opt_extraHttpRequestPar method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -247,46 +239,32 @@ API.Client.PetApi.prototype.getPetById = function(petId, opt_extraHttpRequestPar } /** - * Updates a pet in the store with form data + * Update an existing pet * - * @param {!number} petId ID of pet that needs to be updated - * @param {!string=} opt_name Updated name of the pet - * @param {!string=} opt_status Updated status of the pet + * @param {!Pet} body Pet object that needs to be added to the store * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_status, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + var path = this.basePath_ + '/pet'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - /** @type {!Object} */ - var formParams = {}; - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); + // verify required parameter 'body' is set + if (!body) { + throw new Error('Missing required parameter body when calling updatePet'); } - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - formParams['name'] = opt_name; - - formParams['status'] = opt_status; - /** @type {!Object} */ var httpRequestParams = { - method: 'POST', + method: 'PUT', url: path, - json: false, - - data: this.httpParamSerializer(formParams), - - params: queryParameters, + json: true, + data: body, + params: queryParameters, headers: headerParams }; @@ -298,14 +276,15 @@ API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_st } /** - * Deletes a pet + * Updates a pet in the store with form data * - * @param {!number} petId Pet id to delete - * @param {!string=} opt_apiKey + * @param {!number} petId ID of pet that needs to be updated + * @param {!string=} opt_name Updated name of the pet + * @param {!string=} opt_status Updated status of the pet * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_status, opt_extraHttpRequestParams) { /** @const {string} */ var path = this.basePath_ + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); @@ -315,19 +294,25 @@ API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHtt /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); + /** @type {!Object} */ + var formParams = {}; + // verify required parameter 'petId' is set if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); + throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - headerParams['api_key'] = opt_apiKey; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['name'] = opt_name; + + formParams['status'] = opt_status; /** @type {!Object} */ var httpRequestParams = { - method: 'DELETE', + method: 'POST', url: path, - json: true, - - + json: false, + data: this.httpParamSerializer(formParams), params: queryParameters, headers: headerParams }; @@ -376,9 +361,7 @@ API.Client.PetApi.prototype.uploadFile = function(petId, opt_additionalMetadata, method: 'POST', url: path, json: false, - - data: this.httpParamSerializer(formParams), - + data: this.httpParamSerializer(formParams), params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js b/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js index 9e18eceefcc..d997cc15ce3 100644 --- a/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js +++ b/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js @@ -3,9 +3,8 @@ * Do not edit this file by hand or your changes will be lost next time it is * generated. * - * 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 is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * Version: 1.0.0 - * Generated at: 2016-04-28T06:15:51.482Z * Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen */ /** @@ -45,28 +44,32 @@ API.Client.StoreApi = function($http, $httpParamSerializer, $injector) { API.Client.StoreApi.$inject = ['$http', '$httpParamSerializer', '$injector']; /** - * Returns pet inventories by status - * Returns a map of status codes to quantities + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param {!string} orderId ID of the order that needs to be deleted * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise>} + * @return {!angular.$q.Promise} */ -API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams) { +API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/store/inventory'; + var path = this.basePath_ + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } /** @type {!Object} */ var httpRequestParams = { - method: 'GET', + method: 'DELETE', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -78,34 +81,26 @@ API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams } /** - * Place an order for a pet - * - * @param {!Order} body order placed for purchasing the pet + * Returns pet inventories by status + * Returns a map of status codes to quantities * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise>} */ -API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestParams) { +API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/store/order'; + var path = this.basePath_ + '/store/inventory'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'body' is set - if (!body) { - throw new Error('Missing required parameter body when calling placeOrder'); - } /** @type {!Object} */ var httpRequestParams = { - method: 'POST', + method: 'GET', url: path, json: true, - data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -118,7 +113,7 @@ API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestPa /** * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param {!number} orderId ID of pet that needs to be fetched * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} @@ -142,9 +137,7 @@ API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequ method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -156,34 +149,32 @@ API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequ } /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param {!string} orderId ID of the order that needs to be deleted + * Place an order for a pet + * + * @param {!Order} body order placed for purchasing the pet * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) { +API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + var path = this.basePath_ + '/store/order'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); + // verify required parameter 'body' is set + if (!body) { + throw new Error('Missing required parameter body when calling placeOrder'); } /** @type {!Object} */ var httpRequestParams = { - method: 'DELETE', + method: 'POST', url: path, json: true, - - - params: queryParameters, + data: body, + params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js b/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js index 733f7d65f5a..5a146fc04d6 100644 --- a/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js +++ b/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js @@ -3,9 +3,8 @@ * Do not edit this file by hand or your changes will be lost next time it is * generated. * - * 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 is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * Version: 1.0.0 - * Generated at: 2016-04-28T06:15:51.482Z * Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen */ /** @@ -70,9 +69,7 @@ API.Client.UserApi.prototype.createUser = function(body, opt_extraHttpRequestPar url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -109,9 +106,7 @@ API.Client.UserApi.prototype.createUsersWithArrayInput = function(body, opt_extr url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -148,9 +143,7 @@ API.Client.UserApi.prototype.createUsersWithListInput = function(body, opt_extra url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -162,16 +155,16 @@ API.Client.UserApi.prototype.createUsersWithListInput = function(body, opt_extra } /** - * Logs user into the system - * - * @param {!string} username The user name for login - * @param {!string} password The password for login in clear text + * Delete user + * This can only be done by the logged in user. + * @param {!string} username The name that needs to be deleted * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/login'; + var path = this.basePath_ + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); /** @type {!Object} */ var queryParameters = {}; @@ -180,28 +173,14 @@ API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraH var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'username' is set if (!username) { - throw new Error('Missing required parameter username when calling loginUser'); - } - // verify required parameter 'password' is set - if (!password) { - throw new Error('Missing required parameter password when calling loginUser'); - } - if (username !== undefined) { - queryParameters['username'] = username; - } - - if (password !== undefined) { - queryParameters['password'] = password; + throw new Error('Missing required parameter username when calling deleteUser'); } - /** @type {!Object} */ var httpRequestParams = { - method: 'GET', + method: 'DELETE', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -213,28 +192,32 @@ API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraH } /** - * Logs out current logged in user session + * Get user by user name * + * @param {!string} username The name that needs to be fetched. Use user1 for testing. * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/logout'; + var path = this.basePath_ + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } /** @type {!Object} */ var httpRequestParams = { method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -246,16 +229,16 @@ API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { } /** - * Get user by user name + * Logs user into the system * - * @param {!string} username The name that needs to be fetched. Use user1 for testing. + * @param {!string} username The user name for login + * @param {!string} password The password for login in clear text * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + var path = this.basePath_ + '/user/login'; /** @type {!Object} */ var queryParameters = {}; @@ -264,16 +247,26 @@ API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpReq var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'username' is set if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); + throw new Error('Missing required parameter username when calling loginUser'); + } + // verify required parameter 'password' is set + if (!password) { + throw new Error('Missing required parameter password when calling loginUser'); + } + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; } + /** @type {!Object} */ var httpRequestParams = { method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -285,40 +278,26 @@ API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpReq } /** - * Updated user - * This can only be done by the logged in user. - * @param {!string} username name that need to be deleted - * @param {!User} body Updated user object + * Logs out current logged in user session + * * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + var path = this.basePath_ + '/user/logout'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); - } - // verify required parameter 'body' is set - if (!body) { - throw new Error('Missing required parameter body when calling updateUser'); - } /** @type {!Object} */ var httpRequestParams = { - method: 'PUT', + method: 'GET', url: path, json: true, - data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -330,13 +309,14 @@ API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttp } /** - * Delete user + * Updated user * This can only be done by the logged in user. - * @param {!string} username The name that needs to be deleted + * @param {!string} username name that need to be deleted + * @param {!User} body Updated user object * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttpRequestParams) { /** @const {string} */ var path = this.basePath_ + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -348,16 +328,19 @@ API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpReques var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'username' is set if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); + throw new Error('Missing required parameter username when calling updateUser'); + } + // verify required parameter 'body' is set + if (!body) { + throw new Error('Missing required parameter body when calling updateUser'); } /** @type {!Object} */ var httpRequestParams = { - method: 'DELETE', + method: 'PUT', url: path, json: true, - - - params: queryParameters, + data: body, + params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/javascript-closure-angular/lib/goog/base.js b/samples/client/petstore/javascript-closure-angular/lib/goog/base.js index 58674377024..c1f3b579582 100644 --- a/samples/client/petstore/javascript-closure-angular/lib/goog/base.js +++ b/samples/client/petstore/javascript-closure-angular/lib/goog/base.js @@ -284,7 +284,7 @@ goog.addDependency = function(relPath, provides, requires) { // NOTE(nnaze): The debug DOM loader was included in base.js as an orignal // way to do "debug-mode" development. The dependency system can sometimes -// be confusing, as can the debug DOM loader's asyncronous nature. +// be confusing, as can the debug DOM loader's asynchronous nature. // // With the DOM loader, a call to goog.require() is not blocking -- the // script will not load until some point after the current script. If a diff --git a/samples/client/petstore/javascript-promise/.swagger-codegen-ignore b/samples/client/petstore/javascript-promise/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/javascript-promise/.swagger-codegen-ignore +++ b/samples/client/petstore/javascript-promise/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index 98ee1b5bd7d..051eb9bf4ff 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -6,7 +6,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-29T13:53:04.955-07:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -55,11 +54,10 @@ var SwaggerPetstore = require('swagger_petstore'); var api = new SwaggerPetstore.FakeApi() -var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // {String} To test code injection =end -}; -api.testCodeInjectEnd(opts).then(function() { - console.log('API called successfully.'); +var body = new SwaggerPetstore.Client(); // {Client} client model + +api.testClientModel(body).then(function(data) { + console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); }); @@ -73,9 +71,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*SwaggerPetstore.FakeApi* | [**testCodeInjectEnd**](docs/FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end +*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* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +*SwaggerPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *SwaggerPetstore.PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *SwaggerPetstore.PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -109,11 +107,14 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.Client](docs/Client.md) - [SwaggerPetstore.Dog](docs/Dog.md) + - [SwaggerPetstore.EnumArrays](docs/EnumArrays.md) - [SwaggerPetstore.EnumClass](docs/EnumClass.md) - [SwaggerPetstore.EnumTest](docs/EnumTest.md) - [SwaggerPetstore.FormatTest](docs/FormatTest.md) - [SwaggerPetstore.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [SwaggerPetstore.List](docs/List.md) - [SwaggerPetstore.MapTest](docs/MapTest.md) - [SwaggerPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [SwaggerPetstore.Model200Response](docs/Model200Response.md) @@ -131,6 +132,16 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth @@ -140,9 +151,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/javascript-promise/docs/ApiResponse.md b/samples/client/petstore/javascript-promise/docs/ApiResponse.md index 0ee678b84af..7f023aff601 100644 --- a/samples/client/petstore/javascript-promise/docs/ApiResponse.md +++ b/samples/client/petstore/javascript-promise/docs/ApiResponse.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] +**code** | **Number** | | [optional] **type** | **String** | | [optional] **message** | **String** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/ArrayTest.md b/samples/client/petstore/javascript-promise/docs/ArrayTest.md index a2576512243..e6048e9ea91 100644 --- a/samples/client/petstore/javascript-promise/docs/ArrayTest.md +++ b/samples/client/petstore/javascript-promise/docs/ArrayTest.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **arrayOfString** | **[String]** | | [optional] -**arrayArrayOfInteger** | **[[Integer]]** | | [optional] +**arrayArrayOfInteger** | **[[Number]]** | | [optional] **arrayArrayOfModel** | **[[ReadOnlyFirst]]** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/Category.md b/samples/client/petstore/javascript-promise/docs/Category.md index 47930eb882c..02b2488a27a 100644 --- a/samples/client/petstore/javascript-promise/docs/Category.md +++ b/samples/client/petstore/javascript-promise/docs/Category.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **name** | **String** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/Client.md b/samples/client/petstore/javascript-promise/docs/Client.md new file mode 100644 index 00000000000..6ba28319684 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Client.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/EnumArrays.md b/samples/client/petstore/javascript-promise/docs/EnumArrays.md new file mode 100644 index 00000000000..449a96fdbbd --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/EnumArrays.md @@ -0,0 +1,31 @@ +# SwaggerPetstore.EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[String]** | | [optional] + + + +## Enum: JustSymbolEnum + + +* `GREATER_THAN_OR_EQUAL_TO` (value: `">="`) + +* `DOLLAR` (value: `"$"`) + + + + + +## Enum: [ArrayEnumEnum] + + +* `fish` (value: `"fish"`) + +* `crab` (value: `"crab"`) + + + + diff --git a/samples/client/petstore/javascript-promise/docs/EnumTest.md b/samples/client/petstore/javascript-promise/docs/EnumTest.md index 22c4da11b9d..f66f900778e 100644 --- a/samples/client/petstore/javascript-promise/docs/EnumTest.md +++ b/samples/client/petstore/javascript-promise/docs/EnumTest.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enumString** | **String** | | [optional] -**enumInteger** | **Integer** | | [optional] +**enumInteger** | **Number** | | [optional] **enumNumber** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/FakeApi.md b/samples/client/petstore/javascript-promise/docs/FakeApi.md index c402d82c816..b3bc1ae145f 100644 --- a/samples/client/petstore/javascript-promise/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(opts) + +# **testClientModel** +> Client testClientModel(body) -To test code injection =end +To test \"client\" model ### Example ```javascript @@ -21,11 +21,10 @@ var SwaggerPetstore = require('swagger_petstore'); var apiInstance = new SwaggerPetstore.FakeApi(); -var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // String | To test code injection =end -}; -apiInstance.testCodeInjectEnd(opts).then(function() { - console.log('API called successfully.'); +var body = new SwaggerPetstore.Client(); // Client | client model + +apiInstance.testClientModel(body).then(function(data) { + console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); }); @@ -36,11 +35,11 @@ apiInstance.testCodeInjectEnd(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -null (empty response body) +[**Client**](Client.md) ### Authorization @@ -48,12 +47,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json # **testEndpointParameters** -> testEndpointParameters(_number, _double, _string, _byte, opts) +> testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -62,6 +61,12 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```javascript var SwaggerPetstore = require('swagger_petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure HTTP basic authorization: http_basic_test +var http_basic_test = defaultClient.authentications['http_basic_test']; +http_basic_test.username = 'YOUR USERNAME'; +http_basic_test.password = 'YOUR PASSWORD'; var apiInstance = new SwaggerPetstore.FakeApi(); @@ -69,21 +74,22 @@ var _number = 3.4; // Number | None var _double = 1.2; // Number | None -var _string = "_string_example"; // String | None +var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None var _byte = "B"; // String | None var opts = { - 'integer': 56, // Integer | None - 'int32': 56, // Integer | None - 'int64': 789, // Integer | None + 'integer': 56, // Number | None + 'int32': 56, // Number | None + 'int64': 789, // Number | None '_float': 3.4, // Number | None + '_string': "_string_example", // String | None 'binary': "B", // String | None '_date': new Date("2013-10-20"), // Date | None 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None 'password': "password_example" // String | None }; -apiInstance.testEndpointParameters(_number, _double, _string, _byte, opts).then(function() { +apiInstance.testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -97,12 +103,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **_number** | **Number**| None | **_double** | **Number**| None | - **_string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **String**| None | - **integer** | **Integer**| None | [optional] - **int32** | **Integer**| None | [optional] - **int64** | **Integer**| None | [optional] + **integer** | **Number**| None | [optional] + **int32** | **Number**| None | [optional] + **int64** | **Number**| None | [optional] **_float** | **Number**| None | [optional] + **_string** | **String**| None | [optional] **binary** | **String**| None | [optional] **_date** | **Date**| None | [optional] **dateTime** | **Date**| None | [optional] @@ -114,18 +121,18 @@ null (empty response body) ### Authorization -No authorization required +[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 - -# **testEnumQueryParameters** -> testEnumQueryParameters(opts) + +# **testEnumParameters** +> testEnumParameters(opts) -To test enum query parameters +To test enum parameters ### Example ```javascript @@ -134,11 +141,16 @@ var SwaggerPetstore = require('swagger_petstore'); var apiInstance = new SwaggerPetstore.FakeApi(); var opts = { + 'enumFormStringArray': ["enumFormStringArray_example"], // [String] | Form parameter enum test (string array) + 'enumFormString': "-efg", // String | Form parameter enum test (string) + 'enumHeaderStringArray': ["enumHeaderStringArray_example"], // [String] | Header parameter enum test (string array) + 'enumHeaderString': "-efg", // String | Header parameter enum test (string) + 'enumQueryStringArray': ["enumQueryStringArray_example"], // [String] | Query parameter enum test (string array) 'enumQueryString': "-efg", // String | Query parameter enum test (string) 'enumQueryInteger': 3.4, // Number | Query parameter enum test (double) 'enumQueryDouble': 1.2 // Number | Query parameter enum test (double) }; -apiInstance.testEnumQueryParameters(opts).then(function() { +apiInstance.testEnumParameters(opts).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -150,6 +162,11 @@ apiInstance.testEnumQueryParameters(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**[String]**](String.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**[String]**](String.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**[String]**](String.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] **enumQueryInteger** | **Number**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Number**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/FormatTest.md b/samples/client/petstore/javascript-promise/docs/FormatTest.md index 9600904ee6d..33f4070faf4 100644 --- a/samples/client/petstore/javascript-promise/docs/FormatTest.md +++ b/samples/client/petstore/javascript-promise/docs/FormatTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**integer** | **Integer** | | [optional] -**int32** | **Integer** | | [optional] -**int64** | **Integer** | | [optional] +**integer** | **Number** | | [optional] +**int32** | **Number** | | [optional] +**int64** | **Number** | | [optional] **_number** | **Number** | | **_float** | **Number** | | [optional] **_double** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/List.md b/samples/client/petstore/javascript-promise/docs/List.md new file mode 100644 index 00000000000..12166562e89 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/List.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123List** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/MapTest.md b/samples/client/petstore/javascript-promise/docs/MapTest.md index ae77813d9ce..8550252a3f1 100644 --- a/samples/client/petstore/javascript-promise/docs/MapTest.md +++ b/samples/client/petstore/javascript-promise/docs/MapTest.md @@ -11,6 +11,10 @@ Name | Type | Description | Notes ## Enum: {String: String} +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + diff --git a/samples/client/petstore/javascript-promise/docs/Model200Response.md b/samples/client/petstore/javascript-promise/docs/Model200Response.md index 8f8c94fa93e..f18f963c96d 100644 --- a/samples/client/petstore/javascript-promise/docs/Model200Response.md +++ b/samples/client/petstore/javascript-promise/docs/Model200Response.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **Integer** | | [optional] +**name** | **Number** | | [optional] **_class** | **String** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/ModelReturn.md b/samples/client/petstore/javascript-promise/docs/ModelReturn.md index 88412c87197..b602b39b0c5 100644 --- a/samples/client/petstore/javascript-promise/docs/ModelReturn.md +++ b/samples/client/petstore/javascript-promise/docs/ModelReturn.md @@ -3,6 +3,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_return** | **Integer** | | [optional] +**_return** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/Name.md b/samples/client/petstore/javascript-promise/docs/Name.md index 6c47d402743..51dad9ca578 100644 --- a/samples/client/petstore/javascript-promise/docs/Name.md +++ b/samples/client/petstore/javascript-promise/docs/Name.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **Integer** | | -**snakeCase** | **Integer** | | [optional] +**name** | **Number** | | +**snakeCase** | **Number** | | [optional] **property** | **String** | | [optional] -**_123Number** | **Integer** | | [optional] +**_123Number** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/Order.md b/samples/client/petstore/javascript-promise/docs/Order.md index 95ee5946ed2..6dc0b19cd25 100644 --- a/samples/client/petstore/javascript-promise/docs/Order.md +++ b/samples/client/petstore/javascript-promise/docs/Order.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] -**petId** | **Integer** | | [optional] -**quantity** | **Integer** | | [optional] +**id** | **Number** | | [optional] +**petId** | **Number** | | [optional] +**quantity** | **Number** | | [optional] **shipDate** | **Date** | | [optional] **status** | **String** | Order Status | [optional] **complete** | **Boolean** | | [optional] [default to false] diff --git a/samples/client/petstore/javascript-promise/docs/Pet.md b/samples/client/petstore/javascript-promise/docs/Pet.md index a08333731c0..cae89de06d4 100644 --- a/samples/client/petstore/javascript-promise/docs/Pet.md +++ b/samples/client/petstore/javascript-promise/docs/Pet.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **category** | [**Category**](Category.md) | | [optional] **name** | **String** | | **photoUrls** | **[String]** | | diff --git a/samples/client/petstore/javascript-promise/docs/PetApi.md b/samples/client/petstore/javascript-promise/docs/PetApi.md index da99c0d308c..3c4a3fdade0 100644 --- a/samples/client/petstore/javascript-promise/docs/PetApi.md +++ b/samples/client/petstore/javascript-promise/docs/PetApi.md @@ -81,7 +81,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | Pet id to delete +var petId = 789; // Number | Pet id to delete var opts = { 'apiKey': "apiKey_example" // String | @@ -98,7 +98,7 @@ apiInstance.deletePet(petId, opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| Pet id to delete | + **petId** | **Number**| Pet id to delete | **apiKey** | **String**| | [optional] ### Return type @@ -231,7 +231,7 @@ api_key.apiKey = 'YOUR API KEY'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet to return +var petId = 789; // Number | ID of pet to return apiInstance.getPetById(petId).then(function(data) { console.log('API called successfully. Returned data: ' + data); @@ -245,7 +245,7 @@ apiInstance.getPetById(petId).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet to return | + **petId** | **Number**| ID of pet to return | ### Return type @@ -327,7 +327,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet that needs to be updated +var petId = 789; // Number | ID of pet that needs to be updated var opts = { 'name': "name_example", // String | Updated name of the pet @@ -345,7 +345,7 @@ apiInstance.updatePetWithForm(petId, opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet that needs to be updated | + **petId** | **Number**| ID of pet that needs to be updated | **name** | **String**| Updated name of the pet | [optional] **status** | **String**| Updated status of the pet | [optional] @@ -381,7 +381,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet to update +var petId = 789; // Number | ID of pet to update var opts = { 'additionalMetadata': "additionalMetadata_example", // String | Additional data to pass to server @@ -399,7 +399,7 @@ apiInstance.uploadFile(petId, opts).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet to update | + **petId** | **Number**| ID of pet to update | **additionalMetadata** | **String**| Additional data to pass to server | [optional] **file** | **File**| file to upload | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/SpecialModelName.md b/samples/client/petstore/javascript-promise/docs/SpecialModelName.md index 03dffa54c3f..a204af143a5 100644 --- a/samples/client/petstore/javascript-promise/docs/SpecialModelName.md +++ b/samples/client/petstore/javascript-promise/docs/SpecialModelName.md @@ -3,6 +3,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**specialPropertyName** | **Integer** | | [optional] +**specialPropertyName** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/StoreApi.md b/samples/client/petstore/javascript-promise/docs/StoreApi.md index 6a423e2ca72..8a1f2159b57 100644 --- a/samples/client/petstore/javascript-promise/docs/StoreApi.md +++ b/samples/client/petstore/javascript-promise/docs/StoreApi.md @@ -55,7 +55,7 @@ No authorization required # **getInventory** -> {'String': 'Integer'} getInventory() +> {'String': 'Number'} getInventory() Returns pet inventories by status @@ -86,7 +86,7 @@ This endpoint does not need any parameter. ### Return type -**{'String': 'Integer'}** +**{'String': 'Number'}** ### Authorization @@ -111,7 +111,7 @@ var SwaggerPetstore = require('swagger_petstore'); var apiInstance = new SwaggerPetstore.StoreApi(); -var orderId = 789; // Integer | ID of pet that needs to be fetched +var orderId = 789; // Number | ID of pet that needs to be fetched apiInstance.getOrderById(orderId).then(function(data) { console.log('API called successfully. Returned data: ' + data); @@ -125,7 +125,7 @@ apiInstance.getOrderById(orderId).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **orderId** | **Integer**| ID of pet that needs to be fetched | + **orderId** | **Number**| ID of pet that needs to be fetched | ### Return type diff --git a/samples/client/petstore/javascript-promise/docs/Tag.md b/samples/client/petstore/javascript-promise/docs/Tag.md index 6c109046fb3..c0277cae8ff 100644 --- a/samples/client/petstore/javascript-promise/docs/Tag.md +++ b/samples/client/petstore/javascript-promise/docs/Tag.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **name** | **String** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/User.md b/samples/client/petstore/javascript-promise/docs/User.md index 071fbb46e47..2cac604cfa0 100644 --- a/samples/client/petstore/javascript-promise/docs/User.md +++ b/samples/client/petstore/javascript-promise/docs/User.md @@ -3,13 +3,13 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **username** | **String** | | [optional] **firstName** | **String** | | [optional] **lastName** | **String** | | [optional] **email** | **String** | | [optional] **password** | **String** | | [optional] **phone** | **String** | | [optional] -**userStatus** | **Integer** | User Status | [optional] +**userStatus** | **Number** | User Status | [optional] diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 5ed1bbffeb5..b3d66a68174 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -64,8 +64,9 @@ * @type {Array.} */ this.authentications = { + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, + 'http_basic_test': {type: 'basic'} 'petstore_auth': {type: 'oauth2'}, - 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'} }; /** * The default HTTP headers to be included for all API calls. @@ -154,7 +155,7 @@ /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -206,7 +207,7 @@ /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { @@ -342,7 +343,8 @@ * @param {Array.} contentTypes An array of request MIME types. * @param {Array.} accepts An array of acceptable response MIME types. * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the - * constructor for a complex type. * @returns {Promise} A Promise object. + * constructor for a complex type. + * @returns {Promise} A {@link https://www.promisejs.org/|Promise} object. */ exports.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, diff --git a/samples/client/petstore/javascript-promise/src/api/FakeApi.js b/samples/client/petstore/javascript-promise/src/api/FakeApi.js index 634c4b5e5b2..c4b4a1d8771 100644 --- a/samples/client/petstore/javascript-promise/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise/src/api/FakeApi.js @@ -25,18 +25,18 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient'], factory); + define(['ApiClient', 'model/Client'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')); + module.exports = factory(require('../ApiClient'), require('../model/Client')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - root.SwaggerPetstore.FakeApi = factory(root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.FakeApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Client); } -}(this, function(ApiClient) { +}(this, function(ApiClient, Client) { 'use strict'; /** @@ -58,13 +58,17 @@ /** - * To test code injection =end - * @param {Object} opts Optional parameters - * @param {String} opts.testCodeInjectEnd To test code injection =end + * To test \"client\" model + * @param {module:model/Client} body client model + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Client} */ - this.testCodeInjectEnd = function(opts) { - opts = opts || {}; - var postBody = null; + this.testClientModel = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling testClientModel"; + } var pathParams = { @@ -74,16 +78,15 @@ var headerParams = { }; var formParams = { - 'test code inject */ =end': opts['testCodeInjectEnd'] }; var authNames = []; - var contentTypes = ['application/json', '*/ =end));(phpinfo(']; - var accepts = ['application/json', '*/ end']; - var returnType = null; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = Client; return this.apiClient.callApi( - '/fake', 'PUT', + '/fake', 'PATCH', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); @@ -95,19 +98,21 @@ * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param {Number} _number None * @param {Number} _double None - * @param {String} _string None + * @param {String} patternWithoutDelimiter None * @param {String} _byte None * @param {Object} opts Optional parameters - * @param {Integer} opts.integer None - * @param {Integer} opts.int32 None - * @param {Integer} opts.int64 None + * @param {Number} opts.integer None + * @param {Number} opts.int32 None + * @param {Number} opts.int64 None * @param {Number} opts._float None + * @param {String} opts._string None * @param {String} opts.binary None * @param {Date} opts._date None * @param {Date} opts.dateTime None * @param {String} opts.password None + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ - this.testEndpointParameters = function(_number, _double, _string, _byte, opts) { + this.testEndpointParameters = function(_number, _double, patternWithoutDelimiter, _byte, opts) { opts = opts || {}; var postBody = null; @@ -121,9 +126,9 @@ throw "Missing the required parameter '_double' when calling testEndpointParameters"; } - // verify the required parameter '_string' is set - if (_string == undefined || _string == null) { - throw "Missing the required parameter '_string' when calling testEndpointParameters"; + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == undefined || patternWithoutDelimiter == null) { + throw "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"; } // verify the required parameter '_byte' is set @@ -145,7 +150,8 @@ 'number': _number, 'float': opts['_float'], 'double': _double, - 'string': _string, + 'string': opts['_string'], + 'pattern_without_delimiter': patternWithoutDelimiter, 'byte': _byte, 'binary': opts['binary'], 'date': opts['_date'], @@ -153,7 +159,7 @@ 'password': opts['password'] }; - var authNames = []; + var authNames = ['http_basic_test']; var contentTypes = ['application/xml; charset=utf-8', 'application/json; charset=utf-8']; var accepts = ['application/xml; charset=utf-8', 'application/json; charset=utf-8']; var returnType = null; @@ -167,13 +173,19 @@ /** - * To test enum query parameters + * To test enum parameters * @param {Object} opts Optional parameters + * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) + * @param {module:model/String} opts.enumFormString Form parameter enum test (string) (default to -efg) + * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) + * @param {module:model/String} opts.enumHeaderString Header parameter enum test (string) (default to -efg) + * @param {Array.} opts.enumQueryStringArray Query parameter enum test (string array) * @param {module:model/String} opts.enumQueryString Query parameter enum test (string) (default to -efg) * @param {Number} opts.enumQueryInteger Query parameter enum test (double) * @param {Number} opts.enumQueryDouble Query parameter enum test (double) + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ - this.testEnumQueryParameters = function(opts) { + this.testEnumParameters = function(opts) { opts = opts || {}; var postBody = null; @@ -181,12 +193,17 @@ var pathParams = { }; var queryParams = { + 'enum_query_string_array': this.apiClient.buildCollectionParam(opts['enumQueryStringArray'], 'csv'), + 'enum_query_string': opts['enumQueryString'], 'enum_query_integer': opts['enumQueryInteger'] }; var headerParams = { + 'enum_header_string_array': opts['enumHeaderStringArray'], + 'enum_header_string': opts['enumHeaderString'] }; var formParams = { - 'enum_query_string': opts['enumQueryString'], + 'enum_form_string_array': this.apiClient.buildCollectionParam(opts['enumFormStringArray'], 'csv'), + 'enum_form_string': opts['enumFormString'], 'enum_query_double': opts['enumQueryDouble'] }; diff --git a/samples/client/petstore/javascript-promise/src/api/PetApi.js b/samples/client/petstore/javascript-promise/src/api/PetApi.js index 6a25f1b0cae..203b31905ed 100644 --- a/samples/client/petstore/javascript-promise/src/api/PetApi.js +++ b/samples/client/petstore/javascript-promise/src/api/PetApi.js @@ -61,6 +61,7 @@ * Add a new pet to the store * * @param {module:model/Pet} body Pet object that needs to be added to the store + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.addPet = function(body) { var postBody = body; @@ -96,9 +97,10 @@ /** * Deletes a pet * - * @param {Integer} petId Pet id to delete + * @param {Number} petId Pet id to delete * @param {Object} opts Optional parameters * @param {String} opts.apiKey + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.deletePet = function(petId, opts) { opts = opts || {}; @@ -138,7 +140,7 @@ * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param {Array.} status Status values that need to be considered for filter - * data is of type: {Array.} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.} */ this.findPetsByStatus = function(status) { var postBody = null; @@ -176,7 +178,7 @@ * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param {Array.} tags Tags to filter by - * data is of type: {Array.} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.} */ this.findPetsByTags = function(tags) { var postBody = null; @@ -213,8 +215,8 @@ /** * Find pet by ID * Returns a single pet - * @param {Integer} petId ID of pet to return - * data is of type: {module:model/Pet} + * @param {Number} petId ID of pet to return + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Pet} */ this.getPetById = function(petId) { var postBody = null; @@ -252,6 +254,7 @@ * Update an existing pet * * @param {module:model/Pet} body Pet object that needs to be added to the store + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.updatePet = function(body) { var postBody = body; @@ -287,10 +290,11 @@ /** * Updates a pet in the store with form data * - * @param {Integer} petId ID of pet that needs to be updated + * @param {Number} petId ID of pet that needs to be updated * @param {Object} opts Optional parameters * @param {String} opts.name Updated name of the pet * @param {String} opts.status Updated status of the pet + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.updatePetWithForm = function(petId, opts) { opts = opts || {}; @@ -330,11 +334,11 @@ /** * uploads an image * - * @param {Integer} petId ID of pet to update + * @param {Number} petId ID of pet to update * @param {Object} opts Optional parameters * @param {String} opts.additionalMetadata Additional data to pass to server * @param {File} opts.file file to upload - * data is of type: {module:model/ApiResponse} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ApiResponse} */ this.uploadFile = function(petId, opts) { opts = opts || {}; diff --git a/samples/client/petstore/javascript-promise/src/api/StoreApi.js b/samples/client/petstore/javascript-promise/src/api/StoreApi.js index b9b31984b24..b184af1058e 100644 --- a/samples/client/petstore/javascript-promise/src/api/StoreApi.js +++ b/samples/client/petstore/javascript-promise/src/api/StoreApi.js @@ -61,6 +61,7 @@ * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param {String} orderId ID of the order that needs to be deleted + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.deleteOrder = function(orderId) { var postBody = null; @@ -97,7 +98,7 @@ /** * Returns pet inventories by status * Returns a map of status codes to quantities - * data is of type: {Object.} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Object.} */ this.getInventory = function() { var postBody = null; @@ -115,7 +116,7 @@ var authNames = ['api_key']; var contentTypes = []; var accepts = ['application/json']; - var returnType = {'String': 'Integer'}; + var returnType = {'String': 'Number'}; return this.apiClient.callApi( '/store/inventory', 'GET', @@ -128,8 +129,8 @@ /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param {Integer} orderId ID of pet that needs to be fetched - * data is of type: {module:model/Order} + * @param {Number} orderId ID of pet that needs to be fetched + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Order} */ this.getOrderById = function(orderId) { var postBody = null; @@ -167,7 +168,7 @@ * Place an order for a pet * * @param {module:model/Order} body order placed for purchasing the pet - * data is of type: {module:model/Order} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Order} */ this.placeOrder = function(body) { var postBody = body; diff --git a/samples/client/petstore/javascript-promise/src/api/UserApi.js b/samples/client/petstore/javascript-promise/src/api/UserApi.js index 813c2c443e7..9186f84e2df 100644 --- a/samples/client/petstore/javascript-promise/src/api/UserApi.js +++ b/samples/client/petstore/javascript-promise/src/api/UserApi.js @@ -61,6 +61,7 @@ * Create user * This can only be done by the logged in user. * @param {module:model/User} body Created user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.createUser = function(body) { var postBody = body; @@ -97,6 +98,7 @@ * Creates list of users with given input array * * @param {Array.} body List of user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.createUsersWithArrayInput = function(body) { var postBody = body; @@ -133,6 +135,7 @@ * Creates list of users with given input array * * @param {Array.} body List of user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.createUsersWithListInput = function(body) { var postBody = body; @@ -169,6 +172,7 @@ * Delete user * This can only be done by the logged in user. * @param {String} username The name that needs to be deleted + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.deleteUser = function(username) { var postBody = null; @@ -206,7 +210,7 @@ * Get user by user name * * @param {String} username The name that needs to be fetched. Use user1 for testing. - * data is of type: {module:model/User} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/User} */ this.getUserByName = function(username) { var postBody = null; @@ -245,7 +249,7 @@ * * @param {String} username The user name for login * @param {String} password The password for login in clear text - * data is of type: {'String'} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link 'String'} */ this.loginUser = function(username, password) { var postBody = null; @@ -288,6 +292,7 @@ /** * Logs out current logged in user session * + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.logoutUser = function() { var postBody = null; @@ -320,6 +325,7 @@ * This can only be done by the logged in user. * @param {String} username name that need to be deleted * @param {module:model/User} body Updated user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.updateUser = function(username, body) { var postBody = body; diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js index 84d30e0c98f..5bf5e2c8304 100644 --- a/samples/client/petstore/javascript-promise/src/index.js +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -25,12 +25,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -115,11 +115,21 @@ * @property {module:model/Category} */ Category: Category, + /** + * The Client model constructor. + * @property {module:model/Client} + */ + Client: Client, /** * The Dog model constructor. * @property {module:model/Dog} */ Dog: Dog, + /** + * The EnumArrays model constructor. + * @property {module:model/EnumArrays} + */ + EnumArrays: EnumArrays, /** * The EnumClass model constructor. * @property {module:model/EnumClass} @@ -140,6 +150,11 @@ * @property {module:model/HasOnlyReadOnly} */ HasOnlyReadOnly: HasOnlyReadOnly, + /** + * The List model constructor. + * @property {module:model/List} + */ + List: List, /** * The MapTest model constructor. * @property {module:model/MapTest} diff --git a/samples/client/petstore/javascript-promise/src/model/ApiResponse.js b/samples/client/petstore/javascript-promise/src/model/ApiResponse.js index d800bae7898..8d311baed47 100644 --- a/samples/client/petstore/javascript-promise/src/model/ApiResponse.js +++ b/samples/client/petstore/javascript-promise/src/model/ApiResponse.js @@ -73,7 +73,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('code')) { - obj['code'] = ApiClient.convertToType(data['code'], 'Integer'); + obj['code'] = ApiClient.convertToType(data['code'], 'Number'); } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); @@ -86,7 +86,7 @@ } /** - * @member {Integer} code + * @member {Number} code */ exports.prototype['code'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/ArrayTest.js b/samples/client/petstore/javascript-promise/src/model/ArrayTest.js index 5c260f258a4..7f5d290f57f 100644 --- a/samples/client/petstore/javascript-promise/src/model/ArrayTest.js +++ b/samples/client/petstore/javascript-promise/src/model/ArrayTest.js @@ -76,7 +76,7 @@ obj['array_of_string'] = ApiClient.convertToType(data['array_of_string'], ['String']); } if (data.hasOwnProperty('array_array_of_integer')) { - obj['array_array_of_integer'] = ApiClient.convertToType(data['array_array_of_integer'], [['Integer']]); + obj['array_array_of_integer'] = ApiClient.convertToType(data['array_array_of_integer'], [['Number']]); } if (data.hasOwnProperty('array_array_of_model')) { obj['array_array_of_model'] = ApiClient.convertToType(data['array_array_of_model'], [[ReadOnlyFirst]]); @@ -90,7 +90,7 @@ */ exports.prototype['array_of_string'] = undefined; /** - * @member {Array.>} array_array_of_integer + * @member {Array.>} array_array_of_integer */ exports.prototype['array_array_of_integer'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/Category.js b/samples/client/petstore/javascript-promise/src/model/Category.js index c4b1340c891..4f784006081 100644 --- a/samples/client/petstore/javascript-promise/src/model/Category.js +++ b/samples/client/petstore/javascript-promise/src/model/Category.js @@ -72,7 +72,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); @@ -82,7 +82,7 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/Client.js b/samples/client/petstore/javascript-promise/src/model/Client.js new file mode 100644 index 00000000000..5ecb176007c --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Client.js @@ -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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Client = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The Client model module. + * @module model/Client + * @version 1.0.0 + */ + + /** + * Constructs a new Client. + * @alias module:model/Client + * @class + */ + var exports = function() { + var _this = this; + + + }; + + /** + * Constructs a Client from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Client} obj Optional instance to populate. + * @return {module:model/Client} The populated Client instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('client')) { + obj['client'] = ApiClient.convertToType(data['client'], 'String'); + } + } + return obj; + } + + /** + * @member {String} client + */ + exports.prototype['client'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/EnumArrays.js b/samples/client/petstore/javascript-promise/src/model/EnumArrays.js new file mode 100644 index 00000000000..adfd91990df --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/EnumArrays.js @@ -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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.EnumArrays = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The EnumArrays model module. + * @module model/EnumArrays + * @version 1.0.0 + */ + + /** + * Constructs a new EnumArrays. + * @alias module:model/EnumArrays + * @class + */ + var exports = function() { + var _this = this; + + + + }; + + /** + * Constructs a EnumArrays from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/EnumArrays} obj Optional instance to populate. + * @return {module:model/EnumArrays} The populated EnumArrays instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('just_symbol')) { + obj['just_symbol'] = ApiClient.convertToType(data['just_symbol'], 'String'); + } + if (data.hasOwnProperty('array_enum')) { + obj['array_enum'] = ApiClient.convertToType(data['array_enum'], ['String']); + } + } + return obj; + } + + /** + * @member {module:model/EnumArrays.JustSymbolEnum} just_symbol + */ + exports.prototype['just_symbol'] = undefined; + /** + * @member {Array.} array_enum + */ + exports.prototype['array_enum'] = undefined; + + + /** + * Allowed values for the just_symbol property. + * @enum {String} + * @readonly + */ + exports.JustSymbolEnum = { + /** + * value: ">=" + * @const + */ + "GREATER_THAN_OR_EQUAL_TO": ">=", + /** + * value: "$" + * @const + */ + "DOLLAR": "$" }; + + /** + * Allowed values for the arrayEnum property. + * @enum {String} + * @readonly + */ + exports.ArrayEnumEnum = { + /** + * value: "fish" + * @const + */ + "fish": "fish", + /** + * value: "crab" + * @const + */ + "crab": "crab" }; + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/EnumTest.js b/samples/client/petstore/javascript-promise/src/model/EnumTest.js index 5fe6568b2d5..80476d2d031 100644 --- a/samples/client/petstore/javascript-promise/src/model/EnumTest.js +++ b/samples/client/petstore/javascript-promise/src/model/EnumTest.js @@ -76,7 +76,7 @@ obj['enum_string'] = ApiClient.convertToType(data['enum_string'], 'String'); } if (data.hasOwnProperty('enum_integer')) { - obj['enum_integer'] = ApiClient.convertToType(data['enum_integer'], 'Integer'); + obj['enum_integer'] = ApiClient.convertToType(data['enum_integer'], 'Number'); } if (data.hasOwnProperty('enum_number')) { obj['enum_number'] = ApiClient.convertToType(data['enum_number'], 'Number'); @@ -118,7 +118,7 @@ /** * Allowed values for the enum_integer property. - * @enum {Integer} + * @enum {Number} * @readonly */ exports.EnumIntegerEnum = { diff --git a/samples/client/petstore/javascript-promise/src/model/FormatTest.js b/samples/client/petstore/javascript-promise/src/model/FormatTest.js index 4f6013f9d31..4f4c82f3e6b 100644 --- a/samples/client/petstore/javascript-promise/src/model/FormatTest.js +++ b/samples/client/petstore/javascript-promise/src/model/FormatTest.js @@ -87,13 +87,13 @@ obj = obj || new exports(); if (data.hasOwnProperty('integer')) { - obj['integer'] = ApiClient.convertToType(data['integer'], 'Integer'); + obj['integer'] = ApiClient.convertToType(data['integer'], 'Number'); } if (data.hasOwnProperty('int32')) { - obj['int32'] = ApiClient.convertToType(data['int32'], 'Integer'); + obj['int32'] = ApiClient.convertToType(data['int32'], 'Number'); } if (data.hasOwnProperty('int64')) { - obj['int64'] = ApiClient.convertToType(data['int64'], 'Integer'); + obj['int64'] = ApiClient.convertToType(data['int64'], 'Number'); } if (data.hasOwnProperty('number')) { obj['number'] = ApiClient.convertToType(data['number'], 'Number'); @@ -130,15 +130,15 @@ } /** - * @member {Integer} integer + * @member {Number} integer */ exports.prototype['integer'] = undefined; /** - * @member {Integer} int32 + * @member {Number} int32 */ exports.prototype['int32'] = undefined; /** - * @member {Integer} int64 + * @member {Number} int64 */ exports.prototype['int64'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/List.js b/samples/client/petstore/javascript-promise/src/model/List.js new file mode 100644 index 00000000000..7e88e470df8 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/List.js @@ -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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.List = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The List model module. + * @module model/List + * @version 1.0.0 + */ + + /** + * Constructs a new List. + * @alias module:model/List + * @class + */ + var exports = function() { + var _this = this; + + + }; + + /** + * Constructs a List from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/List} obj Optional instance to populate. + * @return {module:model/List} The populated List instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('123-list')) { + obj['123-list'] = ApiClient.convertToType(data['123-list'], 'String'); + } + } + return obj; + } + + /** + * @member {String} 123-list + */ + exports.prototype['123-list'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Model200Response.js b/samples/client/petstore/javascript-promise/src/model/Model200Response.js index 671d6876a12..7e1b995e012 100644 --- a/samples/client/petstore/javascript-promise/src/model/Model200Response.js +++ b/samples/client/petstore/javascript-promise/src/model/Model200Response.js @@ -73,7 +73,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + obj['name'] = ApiClient.convertToType(data['name'], 'Number'); } if (data.hasOwnProperty('class')) { obj['class'] = ApiClient.convertToType(data['class'], 'String'); @@ -83,7 +83,7 @@ } /** - * @member {Integer} name + * @member {Number} name */ exports.prototype['name'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/ModelReturn.js b/samples/client/petstore/javascript-promise/src/model/ModelReturn.js index 5358484fb21..ca81cd35998 100644 --- a/samples/client/petstore/javascript-promise/src/model/ModelReturn.js +++ b/samples/client/petstore/javascript-promise/src/model/ModelReturn.js @@ -72,14 +72,14 @@ obj = obj || new exports(); if (data.hasOwnProperty('return')) { - obj['return'] = ApiClient.convertToType(data['return'], 'Integer'); + obj['return'] = ApiClient.convertToType(data['return'], 'Number'); } } return obj; } /** - * @member {Integer} return + * @member {Number} return */ exports.prototype['return'] = undefined; diff --git a/samples/client/petstore/javascript-promise/src/model/Name.js b/samples/client/petstore/javascript-promise/src/model/Name.js index 8a50a92c49c..67d343c9af3 100644 --- a/samples/client/petstore/javascript-promise/src/model/Name.js +++ b/samples/client/petstore/javascript-promise/src/model/Name.js @@ -53,7 +53,7 @@ * Model for testing model name same as property name * @alias module:model/Name * @class - * @param name {Integer} + * @param name {Number} */ var exports = function(name) { var _this = this; @@ -76,27 +76,27 @@ obj = obj || new exports(); if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + obj['name'] = ApiClient.convertToType(data['name'], 'Number'); } if (data.hasOwnProperty('snake_case')) { - obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Integer'); + obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Number'); } if (data.hasOwnProperty('property')) { obj['property'] = ApiClient.convertToType(data['property'], 'String'); } if (data.hasOwnProperty('123Number')) { - obj['123Number'] = ApiClient.convertToType(data['123Number'], 'Integer'); + obj['123Number'] = ApiClient.convertToType(data['123Number'], 'Number'); } } return obj; } /** - * @member {Integer} name + * @member {Number} name */ exports.prototype['name'] = undefined; /** - * @member {Integer} snake_case + * @member {Number} snake_case */ exports.prototype['snake_case'] = undefined; /** @@ -104,7 +104,7 @@ */ exports.prototype['property'] = undefined; /** - * @member {Integer} 123Number + * @member {Number} 123Number */ exports.prototype['123Number'] = undefined; diff --git a/samples/client/petstore/javascript-promise/src/model/Order.js b/samples/client/petstore/javascript-promise/src/model/Order.js index f1cdab74f70..fbf719fd674 100644 --- a/samples/client/petstore/javascript-promise/src/model/Order.js +++ b/samples/client/petstore/javascript-promise/src/model/Order.js @@ -76,13 +76,13 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('petId')) { - obj['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); + obj['petId'] = ApiClient.convertToType(data['petId'], 'Number'); } if (data.hasOwnProperty('quantity')) { - obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); + obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Number'); } if (data.hasOwnProperty('shipDate')) { obj['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); @@ -98,15 +98,15 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** - * @member {Integer} petId + * @member {Number} petId */ exports.prototype['petId'] = undefined; /** - * @member {Integer} quantity + * @member {Number} quantity */ exports.prototype['quantity'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/Pet.js b/samples/client/petstore/javascript-promise/src/model/Pet.js index 5575c2087d5..89fbb1d159f 100644 --- a/samples/client/petstore/javascript-promise/src/model/Pet.js +++ b/samples/client/petstore/javascript-promise/src/model/Pet.js @@ -78,7 +78,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('category')) { obj['category'] = Category.constructFromObject(data['category']); @@ -100,7 +100,7 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js b/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js index b4e6e67ea8c..ec064be656b 100644 --- a/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js +++ b/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js @@ -71,14 +71,14 @@ obj = obj || new exports(); if (data.hasOwnProperty('$special[property.name]')) { - obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Integer'); + obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Number'); } } return obj; } /** - * @member {Integer} $special[property.name] + * @member {Number} $special[property.name] */ exports.prototype['$special[property.name]'] = undefined; diff --git a/samples/client/petstore/javascript-promise/src/model/Tag.js b/samples/client/petstore/javascript-promise/src/model/Tag.js index 010263babe3..bcf97c7bad0 100644 --- a/samples/client/petstore/javascript-promise/src/model/Tag.js +++ b/samples/client/petstore/javascript-promise/src/model/Tag.js @@ -72,7 +72,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); @@ -82,7 +82,7 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/User.js b/samples/client/petstore/javascript-promise/src/model/User.js index 1c77bd4bb07..38a1bd1139d 100644 --- a/samples/client/petstore/javascript-promise/src/model/User.js +++ b/samples/client/petstore/javascript-promise/src/model/User.js @@ -78,7 +78,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('username')) { obj['username'] = ApiClient.convertToType(data['username'], 'String'); @@ -99,14 +99,14 @@ obj['phone'] = ApiClient.convertToType(data['phone'], 'String'); } if (data.hasOwnProperty('userStatus')) { - obj['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); + obj['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Number'); } } return obj; } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** @@ -135,7 +135,7 @@ exports.prototype['phone'] = undefined; /** * User Status - * @member {Integer} userStatus + * @member {Number} userStatus */ exports.prototype['userStatus'] = undefined; diff --git a/samples/client/petstore/javascript-promise/test/ApiClientTest.js b/samples/client/petstore/javascript-promise/test/ApiClientTest.js index 085983688bb..ca736876440 100644 --- a/samples/client/petstore/javascript-promise/test/ApiClientTest.js +++ b/samples/client/petstore/javascript-promise/test/ApiClientTest.js @@ -13,6 +13,7 @@ describe('ApiClient', function() { expect(apiClient.basePath).to.be('http://petstore.swagger.io/v2'); expect(apiClient.authentications).to.eql({ petstore_auth: {type: 'oauth2'}, + http_basic_test: {type: 'basic'}, api_key: {type: 'apiKey', 'in': 'header', name: 'api_key'} /* comment out the following as these fake security def (testing purpose) * are removed from the spec, we'll add these back after updating the diff --git a/samples/client/petstore/javascript-promise/test/model/Client.spec.js b/samples/client/petstore/javascript-promise/test/model/Client.spec.js new file mode 100644 index 00000000000..7bba630a29c --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/Client.spec.js @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.Client(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Client', function() { + it('should create an instance of Client', function() { + // uncomment below and update the code to test Client + //var instane = new SwaggerPetstore.Client(); + //expect(instance).to.be.a(SwaggerPetstore.Client); + }); + + it('should have the property client (base name: "client")', function() { + // uncomment below and update the code to test the property client + //var instane = new SwaggerPetstore.Client(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise/test/model/EnumArrays.spec.js b/samples/client/petstore/javascript-promise/test/model/EnumArrays.spec.js new file mode 100644 index 00000000000..2d26fb9920f --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/EnumArrays.spec.js @@ -0,0 +1,82 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.EnumArrays(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('EnumArrays', function() { + it('should create an instance of EnumArrays', function() { + // uncomment below and update the code to test EnumArrays + //var instane = new SwaggerPetstore.EnumArrays(); + //expect(instance).to.be.a(SwaggerPetstore.EnumArrays); + }); + + it('should have the property justSymbol (base name: "just_symbol")', function() { + // uncomment below and update the code to test the property justSymbol + //var instane = new SwaggerPetstore.EnumArrays(); + //expect(instance).to.be(); + }); + + it('should have the property arrayEnum (base name: "array_enum")', function() { + // uncomment below and update the code to test the property arrayEnum + //var instane = new SwaggerPetstore.EnumArrays(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise/test/model/List.spec.js b/samples/client/petstore/javascript-promise/test/model/List.spec.js new file mode 100644 index 00000000000..e73583f9ebc --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/List.spec.js @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.List(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('List', function() { + it('should create an instance of List', function() { + // uncomment below and update the code to test List + //var instane = new SwaggerPetstore.List(); + //expect(instance).to.be.a(SwaggerPetstore.List); + }); + + it('should have the property _123List (base name: "123-list")', function() { + // uncomment below and update the code to test the property _123List + //var instane = new SwaggerPetstore.List(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/.swagger-codegen-ignore b/samples/client/petstore/javascript/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/javascript/.swagger-codegen-ignore +++ b/samples/client/petstore/javascript/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 5478a1c44df..0a54168dd7c 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -6,7 +6,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-29T13:53:00.479-07:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -55,18 +54,17 @@ var SwaggerPetstore = require('swagger_petstore'); var api = new SwaggerPetstore.FakeApi() -var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // {String} To test code injection =end -}; +var body = new SwaggerPetstore.Client(); // {Client} client model + var callback = function(error, data, response) { if (error) { console.error(error); } else { - console.log('API called successfully.'); + console.log('API called successfully. Returned data: ' + data); } }; -api.testCodeInjectEnd(opts, callback); +api.testClientModel(body, callback); ``` @@ -76,9 +74,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*SwaggerPetstore.FakeApi* | [**testCodeInjectEnd**](docs/FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end +*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* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +*SwaggerPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *SwaggerPetstore.PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *SwaggerPetstore.PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -112,11 +110,14 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.Client](docs/Client.md) - [SwaggerPetstore.Dog](docs/Dog.md) + - [SwaggerPetstore.EnumArrays](docs/EnumArrays.md) - [SwaggerPetstore.EnumClass](docs/EnumClass.md) - [SwaggerPetstore.EnumTest](docs/EnumTest.md) - [SwaggerPetstore.FormatTest](docs/FormatTest.md) - [SwaggerPetstore.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [SwaggerPetstore.List](docs/List.md) - [SwaggerPetstore.MapTest](docs/MapTest.md) - [SwaggerPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [SwaggerPetstore.Model200Response](docs/Model200Response.md) @@ -134,6 +135,16 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth @@ -143,9 +154,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/javascript/docs/ApiResponse.md b/samples/client/petstore/javascript/docs/ApiResponse.md index 0ee678b84af..7f023aff601 100644 --- a/samples/client/petstore/javascript/docs/ApiResponse.md +++ b/samples/client/petstore/javascript/docs/ApiResponse.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] +**code** | **Number** | | [optional] **type** | **String** | | [optional] **message** | **String** | | [optional] diff --git a/samples/client/petstore/javascript/docs/ArrayTest.md b/samples/client/petstore/javascript/docs/ArrayTest.md index a2576512243..e6048e9ea91 100644 --- a/samples/client/petstore/javascript/docs/ArrayTest.md +++ b/samples/client/petstore/javascript/docs/ArrayTest.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **arrayOfString** | **[String]** | | [optional] -**arrayArrayOfInteger** | **[[Integer]]** | | [optional] +**arrayArrayOfInteger** | **[[Number]]** | | [optional] **arrayArrayOfModel** | **[[ReadOnlyFirst]]** | | [optional] diff --git a/samples/client/petstore/javascript/docs/Category.md b/samples/client/petstore/javascript/docs/Category.md index 47930eb882c..02b2488a27a 100644 --- a/samples/client/petstore/javascript/docs/Category.md +++ b/samples/client/petstore/javascript/docs/Category.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **name** | **String** | | [optional] diff --git a/samples/client/petstore/javascript/docs/Client.md b/samples/client/petstore/javascript/docs/Client.md new file mode 100644 index 00000000000..6ba28319684 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Client.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/EnumArrays.md b/samples/client/petstore/javascript/docs/EnumArrays.md new file mode 100644 index 00000000000..449a96fdbbd --- /dev/null +++ b/samples/client/petstore/javascript/docs/EnumArrays.md @@ -0,0 +1,31 @@ +# SwaggerPetstore.EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[String]** | | [optional] + + + +## Enum: JustSymbolEnum + + +* `GREATER_THAN_OR_EQUAL_TO` (value: `">="`) + +* `DOLLAR` (value: `"$"`) + + + + + +## Enum: [ArrayEnumEnum] + + +* `fish` (value: `"fish"`) + +* `crab` (value: `"crab"`) + + + + diff --git a/samples/client/petstore/javascript/docs/EnumTest.md b/samples/client/petstore/javascript/docs/EnumTest.md index 22c4da11b9d..f66f900778e 100644 --- a/samples/client/petstore/javascript/docs/EnumTest.md +++ b/samples/client/petstore/javascript/docs/EnumTest.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enumString** | **String** | | [optional] -**enumInteger** | **Integer** | | [optional] +**enumInteger** | **Number** | | [optional] **enumNumber** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index cdb5c02e13f..4be1079607b 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(opts) + +# **testClientModel** +> Client testClientModel(body) -To test code injection =end +To test \"client\" model ### Example ```javascript @@ -21,29 +21,28 @@ var SwaggerPetstore = require('swagger_petstore'); var apiInstance = new SwaggerPetstore.FakeApi(); -var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // String | To test code injection =end -}; +var body = new SwaggerPetstore.Client(); // Client | client model + var callback = function(error, data, response) { if (error) { console.error(error); } else { - console.log('API called successfully.'); + console.log('API called successfully. Returned data: ' + data); } }; -apiInstance.testCodeInjectEnd(opts, callback); +apiInstance.testClientModel(body, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -null (empty response body) +[**Client**](Client.md) ### Authorization @@ -51,12 +50,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json # **testEndpointParameters** -> testEndpointParameters(_number, _double, _string, _byte, opts) +> testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -65,6 +64,12 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```javascript var SwaggerPetstore = require('swagger_petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure HTTP basic authorization: http_basic_test +var http_basic_test = defaultClient.authentications['http_basic_test']; +http_basic_test.username = 'YOUR USERNAME'; +http_basic_test.password = 'YOUR PASSWORD'; var apiInstance = new SwaggerPetstore.FakeApi(); @@ -72,19 +77,21 @@ var _number = 3.4; // Number | None var _double = 1.2; // Number | None -var _string = "_string_example"; // String | None +var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None var _byte = "B"; // String | None var opts = { - 'integer': 56, // Integer | None - 'int32': 56, // Integer | None - 'int64': 789, // Integer | None + 'integer': 56, // Number | None + 'int32': 56, // Number | None + 'int64': 789, // Number | None '_float': 3.4, // Number | None + '_string': "_string_example", // String | None 'binary': "B", // String | None '_date': new Date("2013-10-20"), // Date | None 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None - 'password': "password_example" // String | None + 'password': "password_example", // String | None + 'callback': "callback_example" // String | None }; var callback = function(error, data, response) { @@ -94,7 +101,7 @@ var callback = function(error, data, response) { console.log('API called successfully.'); } }; -apiInstance.testEndpointParameters(_number, _double, _string, _byte, opts, callback); +apiInstance.testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts, callback); ``` ### Parameters @@ -103,16 +110,18 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **_number** | **Number**| None | **_double** | **Number**| None | - **_string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **String**| None | - **integer** | **Integer**| None | [optional] - **int32** | **Integer**| None | [optional] - **int64** | **Integer**| None | [optional] + **integer** | **Number**| None | [optional] + **int32** | **Number**| None | [optional] + **int64** | **Number**| None | [optional] **_float** | **Number**| None | [optional] + **_string** | **String**| None | [optional] **binary** | **String**| None | [optional] **_date** | **Date**| None | [optional] **dateTime** | **Date**| None | [optional] **password** | **String**| None | [optional] + **callback** | **String**| None | [optional] ### Return type @@ -120,18 +129,18 @@ null (empty response body) ### Authorization -No authorization required +[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 - -# **testEnumQueryParameters** -> testEnumQueryParameters(opts) + +# **testEnumParameters** +> testEnumParameters(opts) -To test enum query parameters +To test enum parameters ### Example ```javascript @@ -140,6 +149,11 @@ var SwaggerPetstore = require('swagger_petstore'); var apiInstance = new SwaggerPetstore.FakeApi(); var opts = { + 'enumFormStringArray': ["enumFormStringArray_example"], // [String] | Form parameter enum test (string array) + 'enumFormString': "-efg", // String | Form parameter enum test (string) + 'enumHeaderStringArray': ["enumHeaderStringArray_example"], // [String] | Header parameter enum test (string array) + 'enumHeaderString': "-efg", // String | Header parameter enum test (string) + 'enumQueryStringArray': ["enumQueryStringArray_example"], // [String] | Query parameter enum test (string array) 'enumQueryString': "-efg", // String | Query parameter enum test (string) 'enumQueryInteger': 3.4, // Number | Query parameter enum test (double) 'enumQueryDouble': 1.2 // Number | Query parameter enum test (double) @@ -152,13 +166,18 @@ var callback = function(error, data, response) { console.log('API called successfully.'); } }; -apiInstance.testEnumQueryParameters(opts, callback); +apiInstance.testEnumParameters(opts, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**[String]**](String.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**[String]**](String.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**[String]**](String.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] **enumQueryInteger** | **Number**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Number**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/javascript/docs/FormatTest.md b/samples/client/petstore/javascript/docs/FormatTest.md index 9600904ee6d..33f4070faf4 100644 --- a/samples/client/petstore/javascript/docs/FormatTest.md +++ b/samples/client/petstore/javascript/docs/FormatTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**integer** | **Integer** | | [optional] -**int32** | **Integer** | | [optional] -**int64** | **Integer** | | [optional] +**integer** | **Number** | | [optional] +**int32** | **Number** | | [optional] +**int64** | **Number** | | [optional] **_number** | **Number** | | **_float** | **Number** | | [optional] **_double** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript/docs/List.md b/samples/client/petstore/javascript/docs/List.md new file mode 100644 index 00000000000..12166562e89 --- /dev/null +++ b/samples/client/petstore/javascript/docs/List.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123List** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/MapTest.md b/samples/client/petstore/javascript/docs/MapTest.md index ae77813d9ce..8550252a3f1 100644 --- a/samples/client/petstore/javascript/docs/MapTest.md +++ b/samples/client/petstore/javascript/docs/MapTest.md @@ -11,6 +11,10 @@ Name | Type | Description | Notes ## Enum: {String: String} +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + diff --git a/samples/client/petstore/javascript/docs/Model200Response.md b/samples/client/petstore/javascript/docs/Model200Response.md index 8f8c94fa93e..f18f963c96d 100644 --- a/samples/client/petstore/javascript/docs/Model200Response.md +++ b/samples/client/petstore/javascript/docs/Model200Response.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **Integer** | | [optional] +**name** | **Number** | | [optional] **_class** | **String** | | [optional] diff --git a/samples/client/petstore/javascript/docs/ModelReturn.md b/samples/client/petstore/javascript/docs/ModelReturn.md index 88412c87197..b602b39b0c5 100644 --- a/samples/client/petstore/javascript/docs/ModelReturn.md +++ b/samples/client/petstore/javascript/docs/ModelReturn.md @@ -3,6 +3,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_return** | **Integer** | | [optional] +**_return** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript/docs/Name.md b/samples/client/petstore/javascript/docs/Name.md index 6c47d402743..51dad9ca578 100644 --- a/samples/client/petstore/javascript/docs/Name.md +++ b/samples/client/petstore/javascript/docs/Name.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **Integer** | | -**snakeCase** | **Integer** | | [optional] +**name** | **Number** | | +**snakeCase** | **Number** | | [optional] **property** | **String** | | [optional] -**_123Number** | **Integer** | | [optional] +**_123Number** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript/docs/Order.md b/samples/client/petstore/javascript/docs/Order.md index 95ee5946ed2..6dc0b19cd25 100644 --- a/samples/client/petstore/javascript/docs/Order.md +++ b/samples/client/petstore/javascript/docs/Order.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] -**petId** | **Integer** | | [optional] -**quantity** | **Integer** | | [optional] +**id** | **Number** | | [optional] +**petId** | **Number** | | [optional] +**quantity** | **Number** | | [optional] **shipDate** | **Date** | | [optional] **status** | **String** | Order Status | [optional] **complete** | **Boolean** | | [optional] [default to false] diff --git a/samples/client/petstore/javascript/docs/Pet.md b/samples/client/petstore/javascript/docs/Pet.md index a08333731c0..cae89de06d4 100644 --- a/samples/client/petstore/javascript/docs/Pet.md +++ b/samples/client/petstore/javascript/docs/Pet.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **category** | [**Category**](Category.md) | | [optional] **name** | **String** | | **photoUrls** | **[String]** | | diff --git a/samples/client/petstore/javascript/docs/PetApi.md b/samples/client/petstore/javascript/docs/PetApi.md index 95fd1b1e0aa..f38e66a0232 100644 --- a/samples/client/petstore/javascript/docs/PetApi.md +++ b/samples/client/petstore/javascript/docs/PetApi.md @@ -84,7 +84,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | Pet id to delete +var petId = 789; // Number | Pet id to delete var opts = { 'apiKey': "apiKey_example" // String | @@ -104,7 +104,7 @@ apiInstance.deletePet(petId, opts, callback); Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| Pet id to delete | + **petId** | **Number**| Pet id to delete | **apiKey** | **String**| | [optional] ### Return type @@ -243,7 +243,7 @@ api_key.apiKey = 'YOUR API KEY'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet to return +var petId = 789; // Number | ID of pet to return var callback = function(error, data, response) { @@ -260,7 +260,7 @@ apiInstance.getPetById(petId, callback); Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet to return | + **petId** | **Number**| ID of pet to return | ### Return type @@ -345,7 +345,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet that needs to be updated +var petId = 789; // Number | ID of pet that needs to be updated var opts = { 'name': "name_example", // String | Updated name of the pet @@ -366,7 +366,7 @@ apiInstance.updatePetWithForm(petId, opts, callback); Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet that needs to be updated | + **petId** | **Number**| ID of pet that needs to be updated | **name** | **String**| Updated name of the pet | [optional] **status** | **String**| Updated status of the pet | [optional] @@ -402,7 +402,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet to update +var petId = 789; // Number | ID of pet to update var opts = { 'additionalMetadata': "additionalMetadata_example", // String | Additional data to pass to server @@ -423,7 +423,7 @@ apiInstance.uploadFile(petId, opts, callback); Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet to update | + **petId** | **Number**| ID of pet to update | **additionalMetadata** | **String**| Additional data to pass to server | [optional] **file** | **File**| file to upload | [optional] diff --git a/samples/client/petstore/javascript/docs/SpecialModelName.md b/samples/client/petstore/javascript/docs/SpecialModelName.md index 03dffa54c3f..a204af143a5 100644 --- a/samples/client/petstore/javascript/docs/SpecialModelName.md +++ b/samples/client/petstore/javascript/docs/SpecialModelName.md @@ -3,6 +3,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**specialPropertyName** | **Integer** | | [optional] +**specialPropertyName** | **Number** | | [optional] diff --git a/samples/client/petstore/javascript/docs/StoreApi.md b/samples/client/petstore/javascript/docs/StoreApi.md index 2e5ebf30259..9f35d92b004 100644 --- a/samples/client/petstore/javascript/docs/StoreApi.md +++ b/samples/client/petstore/javascript/docs/StoreApi.md @@ -58,7 +58,7 @@ No authorization required # **getInventory** -> {'String': 'Integer'} getInventory() +> {'String': 'Number'} getInventory() Returns pet inventories by status @@ -92,7 +92,7 @@ This endpoint does not need any parameter. ### Return type -**{'String': 'Integer'}** +**{'String': 'Number'}** ### Authorization @@ -117,7 +117,7 @@ var SwaggerPetstore = require('swagger_petstore'); var apiInstance = new SwaggerPetstore.StoreApi(); -var orderId = 789; // Integer | ID of pet that needs to be fetched +var orderId = 789; // Number | ID of pet that needs to be fetched var callback = function(error, data, response) { @@ -134,7 +134,7 @@ apiInstance.getOrderById(orderId, callback); Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **orderId** | **Integer**| ID of pet that needs to be fetched | + **orderId** | **Number**| ID of pet that needs to be fetched | ### Return type diff --git a/samples/client/petstore/javascript/docs/Tag.md b/samples/client/petstore/javascript/docs/Tag.md index 6c109046fb3..c0277cae8ff 100644 --- a/samples/client/petstore/javascript/docs/Tag.md +++ b/samples/client/petstore/javascript/docs/Tag.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **name** | **String** | | [optional] diff --git a/samples/client/petstore/javascript/docs/User.md b/samples/client/petstore/javascript/docs/User.md index 071fbb46e47..2cac604cfa0 100644 --- a/samples/client/petstore/javascript/docs/User.md +++ b/samples/client/petstore/javascript/docs/User.md @@ -3,13 +3,13 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **Integer** | | [optional] +**id** | **Number** | | [optional] **username** | **String** | | [optional] **firstName** | **String** | | [optional] **lastName** | **String** | | [optional] **email** | **String** | | [optional] **password** | **String** | | [optional] **phone** | **String** | | [optional] -**userStatus** | **Integer** | User Status | [optional] +**userStatus** | **Number** | User Status | [optional] diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 96f99848208..720b9417343 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -64,8 +64,9 @@ * @type {Array.} */ this.authentications = { - 'petstore_auth': {type: 'oauth2'}, - 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'} + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, + 'http_basic_test': {type: 'basic'}, + 'petstore_auth': {type: 'oauth2'} }; /** * The default HTTP headers to be included for all API calls. @@ -154,7 +155,7 @@ /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -206,7 +207,7 @@ /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { @@ -376,7 +377,10 @@ var contentType = this.jsonPreferredMime(contentTypes); if (contentType) { - request.type(contentType); + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } } else if (!request.header['Content-Type']) { request.type('application/json'); } diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index 917edf2108d..edda32926dc 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -25,18 +25,18 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient'], factory); + define(['ApiClient', 'model/Client'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')); + module.exports = factory(require('../ApiClient'), require('../model/Client')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - root.SwaggerPetstore.FakeApi = factory(root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.FakeApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Client); } -}(this, function(ApiClient) { +}(this, function(ApiClient, Client) { 'use strict'; /** @@ -57,22 +57,26 @@ /** - * Callback function to receive the result of the testCodeInjectEnd operation. - * @callback module:api/FakeApi~testCodeInjectEndCallback + * Callback function to receive the result of the testClientModel operation. + * @callback module:api/FakeApi~testClientModelCallback * @param {String} error Error message, if any. - * @param data This operation does not return a value. + * @param {module:model/Client} data The data returned by the service call. * @param {String} response The complete HTTP response. */ /** - * To test code injection =end - * @param {Object} opts Optional parameters - * @param {String} opts.testCodeInjectEnd To test code injection =end - * @param {module:api/FakeApi~testCodeInjectEndCallback} callback The callback function, accepting three arguments: error, data, response + * To test \"client\" model + * @param {module:model/Client} body client model + * @param {module:api/FakeApi~testClientModelCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/Client} */ - this.testCodeInjectEnd = function(opts, callback) { - opts = opts || {}; - var postBody = null; + this.testClientModel = function(body, callback) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling testClientModel"; + } var pathParams = { @@ -82,16 +86,15 @@ var headerParams = { }; var formParams = { - 'test code inject */ =end': opts['testCodeInjectEnd'] }; var authNames = []; - var contentTypes = ['application/json', '*/ =end));(phpinfo(']; - var accepts = ['application/json', '*/ end']; - var returnType = null; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = Client; return this.apiClient.callApi( - '/fake', 'PUT', + '/fake', 'PATCH', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); @@ -110,20 +113,22 @@ * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param {Number} _number None * @param {Number} _double None - * @param {String} _string None + * @param {String} patternWithoutDelimiter None * @param {String} _byte None * @param {Object} opts Optional parameters - * @param {Integer} opts.integer None - * @param {Integer} opts.int32 None - * @param {Integer} opts.int64 None + * @param {Number} opts.integer None + * @param {Number} opts.int32 None + * @param {Number} opts.int64 None * @param {Number} opts._float None + * @param {String} opts._string None * @param {String} opts.binary None * @param {Date} opts._date None * @param {Date} opts.dateTime None * @param {String} opts.password None + * @param {String} opts.callback None * @param {module:api/FakeApi~testEndpointParametersCallback} callback The callback function, accepting three arguments: error, data, response */ - this.testEndpointParameters = function(_number, _double, _string, _byte, opts, callback) { + this.testEndpointParameters = function(_number, _double, patternWithoutDelimiter, _byte, opts, callback) { opts = opts || {}; var postBody = null; @@ -137,9 +142,9 @@ throw "Missing the required parameter '_double' when calling testEndpointParameters"; } - // verify the required parameter '_string' is set - if (_string == undefined || _string == null) { - throw "Missing the required parameter '_string' when calling testEndpointParameters"; + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == undefined || patternWithoutDelimiter == null) { + throw "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"; } // verify the required parameter '_byte' is set @@ -161,15 +166,17 @@ 'number': _number, 'float': opts['_float'], 'double': _double, - 'string': _string, + 'string': opts['_string'], + 'pattern_without_delimiter': patternWithoutDelimiter, 'byte': _byte, 'binary': opts['binary'], 'date': opts['_date'], 'dateTime': opts['dateTime'], - 'password': opts['password'] + 'password': opts['password'], + 'callback': opts['callback'] }; - var authNames = []; + var authNames = ['http_basic_test']; var contentTypes = ['application/xml; charset=utf-8', 'application/json; charset=utf-8']; var accepts = ['application/xml; charset=utf-8', 'application/json; charset=utf-8']; var returnType = null; @@ -182,22 +189,27 @@ } /** - * Callback function to receive the result of the testEnumQueryParameters operation. - * @callback module:api/FakeApi~testEnumQueryParametersCallback + * Callback function to receive the result of the testEnumParameters operation. + * @callback module:api/FakeApi~testEnumParametersCallback * @param {String} error Error message, if any. * @param data This operation does not return a value. * @param {String} response The complete HTTP response. */ /** - * To test enum query parameters + * To test enum parameters * @param {Object} opts Optional parameters + * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) + * @param {module:model/String} opts.enumFormString Form parameter enum test (string) (default to -efg) + * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) + * @param {module:model/String} opts.enumHeaderString Header parameter enum test (string) (default to -efg) + * @param {Array.} opts.enumQueryStringArray Query parameter enum test (string array) * @param {module:model/String} opts.enumQueryString Query parameter enum test (string) (default to -efg) * @param {Number} opts.enumQueryInteger Query parameter enum test (double) * @param {Number} opts.enumQueryDouble Query parameter enum test (double) - * @param {module:api/FakeApi~testEnumQueryParametersCallback} callback The callback function, accepting three arguments: error, data, response + * @param {module:api/FakeApi~testEnumParametersCallback} callback The callback function, accepting three arguments: error, data, response */ - this.testEnumQueryParameters = function(opts, callback) { + this.testEnumParameters = function(opts, callback) { opts = opts || {}; var postBody = null; @@ -205,12 +217,17 @@ var pathParams = { }; var queryParams = { + 'enum_query_string_array': this.apiClient.buildCollectionParam(opts['enumQueryStringArray'], 'csv'), + 'enum_query_string': opts['enumQueryString'], 'enum_query_integer': opts['enumQueryInteger'] }; var headerParams = { + 'enum_header_string_array': opts['enumHeaderStringArray'], + 'enum_header_string': opts['enumHeaderString'] }; var formParams = { - 'enum_query_string': opts['enumQueryString'], + 'enum_form_string_array': this.apiClient.buildCollectionParam(opts['enumFormStringArray'], 'csv'), + 'enum_form_string': opts['enumFormString'], 'enum_query_double': opts['enumQueryDouble'] }; diff --git a/samples/client/petstore/javascript/src/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js index 9f28a18cf87..aae8c9844d0 100644 --- a/samples/client/petstore/javascript/src/api/PetApi.js +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -111,7 +111,7 @@ /** * Deletes a pet * - * @param {Integer} petId Pet id to delete + * @param {Number} petId Pet id to delete * @param {Object} opts Optional parameters * @param {String} opts.apiKey * @param {module:api/PetApi~deletePetCallback} callback The callback function, accepting three arguments: error, data, response @@ -162,7 +162,7 @@ * Multiple status values can be provided with comma separated strings * @param {Array.} status Status values that need to be considered for filter * @param {module:api/PetApi~findPetsByStatusCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {Array.} + * data is of type: {@link Array.} */ this.findPetsByStatus = function(status, callback) { var postBody = null; @@ -208,7 +208,7 @@ * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param {Array.} tags Tags to filter by * @param {module:api/PetApi~findPetsByTagsCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {Array.} + * data is of type: {@link Array.} */ this.findPetsByTags = function(tags, callback) { var postBody = null; @@ -252,9 +252,9 @@ /** * Find pet by ID * Returns a single pet - * @param {Integer} petId ID of pet to return + * @param {Number} petId ID of pet to return * @param {module:api/PetApi~getPetByIdCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/Pet} + * data is of type: {@link module:model/Pet} */ this.getPetById = function(petId, callback) { var postBody = null; @@ -342,7 +342,7 @@ /** * Updates a pet in the store with form data * - * @param {Integer} petId ID of pet that needs to be updated + * @param {Number} petId ID of pet that needs to be updated * @param {Object} opts Optional parameters * @param {String} opts.name Updated name of the pet * @param {String} opts.status Updated status of the pet @@ -393,12 +393,12 @@ /** * uploads an image * - * @param {Integer} petId ID of pet to update + * @param {Number} petId ID of pet to update * @param {Object} opts Optional parameters * @param {String} opts.additionalMetadata Additional data to pass to server * @param {File} opts.file file to upload * @param {module:api/PetApi~uploadFileCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/ApiResponse} + * data is of type: {@link module:model/ApiResponse} */ this.uploadFile = function(petId, opts, callback) { opts = opts || {}; diff --git a/samples/client/petstore/javascript/src/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js index 93222f64e49..5290e1bec0f 100644 --- a/samples/client/petstore/javascript/src/api/StoreApi.js +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -105,7 +105,7 @@ * Callback function to receive the result of the getInventory operation. * @callback module:api/StoreApi~getInventoryCallback * @param {String} error Error message, if any. - * @param {Object.} data The data returned by the service call. + * @param {Object.} data The data returned by the service call. * @param {String} response The complete HTTP response. */ @@ -113,7 +113,7 @@ * Returns pet inventories by status * Returns a map of status codes to quantities * @param {module:api/StoreApi~getInventoryCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {Object.} + * data is of type: {@link Object.} */ this.getInventory = function(callback) { var postBody = null; @@ -131,7 +131,7 @@ var authNames = ['api_key']; var contentTypes = []; var accepts = ['application/json']; - var returnType = {'String': 'Integer'}; + var returnType = {'String': 'Number'}; return this.apiClient.callApi( '/store/inventory', 'GET', @@ -151,9 +151,9 @@ /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param {Integer} orderId ID of pet that needs to be fetched + * @param {Number} orderId ID of pet that needs to be fetched * @param {module:api/StoreApi~getOrderByIdCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/Order} + * data is of type: {@link module:model/Order} */ this.getOrderById = function(orderId, callback) { var postBody = null; @@ -199,7 +199,7 @@ * * @param {module:model/Order} body order placed for purchasing the pet * @param {module:api/StoreApi~placeOrderCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/Order} + * data is of type: {@link module:model/Order} */ this.placeOrder = function(body, callback) { var postBody = body; diff --git a/samples/client/petstore/javascript/src/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js index ff450dfb9a5..b5234f1881b 100644 --- a/samples/client/petstore/javascript/src/api/UserApi.js +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -246,7 +246,7 @@ * * @param {String} username The name that needs to be fetched. Use user1 for testing. * @param {module:api/UserApi~getUserByNameCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/User} + * data is of type: {@link module:model/User} */ this.getUserByName = function(username, callback) { var postBody = null; @@ -293,7 +293,7 @@ * @param {String} username The user name for login * @param {String} password The password for login in clear text * @param {module:api/UserApi~loginUserCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {'String'} + * data is of type: {@link 'String'} */ this.loginUser = function(username, password, callback) { var postBody = null; diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 84d30e0c98f..5bf5e2c8304 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -25,12 +25,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -115,11 +115,21 @@ * @property {module:model/Category} */ Category: Category, + /** + * The Client model constructor. + * @property {module:model/Client} + */ + Client: Client, /** * The Dog model constructor. * @property {module:model/Dog} */ Dog: Dog, + /** + * The EnumArrays model constructor. + * @property {module:model/EnumArrays} + */ + EnumArrays: EnumArrays, /** * The EnumClass model constructor. * @property {module:model/EnumClass} @@ -140,6 +150,11 @@ * @property {module:model/HasOnlyReadOnly} */ HasOnlyReadOnly: HasOnlyReadOnly, + /** + * The List model constructor. + * @property {module:model/List} + */ + List: List, /** * The MapTest model constructor. * @property {module:model/MapTest} diff --git a/samples/client/petstore/javascript/src/model/ApiResponse.js b/samples/client/petstore/javascript/src/model/ApiResponse.js index d800bae7898..8d311baed47 100644 --- a/samples/client/petstore/javascript/src/model/ApiResponse.js +++ b/samples/client/petstore/javascript/src/model/ApiResponse.js @@ -73,7 +73,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('code')) { - obj['code'] = ApiClient.convertToType(data['code'], 'Integer'); + obj['code'] = ApiClient.convertToType(data['code'], 'Number'); } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); @@ -86,7 +86,7 @@ } /** - * @member {Integer} code + * @member {Number} code */ exports.prototype['code'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/ArrayTest.js b/samples/client/petstore/javascript/src/model/ArrayTest.js index 5c260f258a4..7f5d290f57f 100644 --- a/samples/client/petstore/javascript/src/model/ArrayTest.js +++ b/samples/client/petstore/javascript/src/model/ArrayTest.js @@ -76,7 +76,7 @@ obj['array_of_string'] = ApiClient.convertToType(data['array_of_string'], ['String']); } if (data.hasOwnProperty('array_array_of_integer')) { - obj['array_array_of_integer'] = ApiClient.convertToType(data['array_array_of_integer'], [['Integer']]); + obj['array_array_of_integer'] = ApiClient.convertToType(data['array_array_of_integer'], [['Number']]); } if (data.hasOwnProperty('array_array_of_model')) { obj['array_array_of_model'] = ApiClient.convertToType(data['array_array_of_model'], [[ReadOnlyFirst]]); @@ -90,7 +90,7 @@ */ exports.prototype['array_of_string'] = undefined; /** - * @member {Array.>} array_array_of_integer + * @member {Array.>} array_array_of_integer */ exports.prototype['array_array_of_integer'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/Category.js b/samples/client/petstore/javascript/src/model/Category.js index c4b1340c891..4f784006081 100644 --- a/samples/client/petstore/javascript/src/model/Category.js +++ b/samples/client/petstore/javascript/src/model/Category.js @@ -72,7 +72,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); @@ -82,7 +82,7 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/Client.js b/samples/client/petstore/javascript/src/model/Client.js new file mode 100644 index 00000000000..5ecb176007c --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Client.js @@ -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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Client = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The Client model module. + * @module model/Client + * @version 1.0.0 + */ + + /** + * Constructs a new Client. + * @alias module:model/Client + * @class + */ + var exports = function() { + var _this = this; + + + }; + + /** + * Constructs a Client from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Client} obj Optional instance to populate. + * @return {module:model/Client} The populated Client instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('client')) { + obj['client'] = ApiClient.convertToType(data['client'], 'String'); + } + } + return obj; + } + + /** + * @member {String} client + */ + exports.prototype['client'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/EnumArrays.js b/samples/client/petstore/javascript/src/model/EnumArrays.js new file mode 100644 index 00000000000..adfd91990df --- /dev/null +++ b/samples/client/petstore/javascript/src/model/EnumArrays.js @@ -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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.EnumArrays = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The EnumArrays model module. + * @module model/EnumArrays + * @version 1.0.0 + */ + + /** + * Constructs a new EnumArrays. + * @alias module:model/EnumArrays + * @class + */ + var exports = function() { + var _this = this; + + + + }; + + /** + * Constructs a EnumArrays from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/EnumArrays} obj Optional instance to populate. + * @return {module:model/EnumArrays} The populated EnumArrays instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('just_symbol')) { + obj['just_symbol'] = ApiClient.convertToType(data['just_symbol'], 'String'); + } + if (data.hasOwnProperty('array_enum')) { + obj['array_enum'] = ApiClient.convertToType(data['array_enum'], ['String']); + } + } + return obj; + } + + /** + * @member {module:model/EnumArrays.JustSymbolEnum} just_symbol + */ + exports.prototype['just_symbol'] = undefined; + /** + * @member {Array.} array_enum + */ + exports.prototype['array_enum'] = undefined; + + + /** + * Allowed values for the just_symbol property. + * @enum {String} + * @readonly + */ + exports.JustSymbolEnum = { + /** + * value: ">=" + * @const + */ + "GREATER_THAN_OR_EQUAL_TO": ">=", + /** + * value: "$" + * @const + */ + "DOLLAR": "$" }; + + /** + * Allowed values for the arrayEnum property. + * @enum {String} + * @readonly + */ + exports.ArrayEnumEnum = { + /** + * value: "fish" + * @const + */ + "fish": "fish", + /** + * value: "crab" + * @const + */ + "crab": "crab" }; + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/EnumTest.js b/samples/client/petstore/javascript/src/model/EnumTest.js index 5fe6568b2d5..80476d2d031 100644 --- a/samples/client/petstore/javascript/src/model/EnumTest.js +++ b/samples/client/petstore/javascript/src/model/EnumTest.js @@ -76,7 +76,7 @@ obj['enum_string'] = ApiClient.convertToType(data['enum_string'], 'String'); } if (data.hasOwnProperty('enum_integer')) { - obj['enum_integer'] = ApiClient.convertToType(data['enum_integer'], 'Integer'); + obj['enum_integer'] = ApiClient.convertToType(data['enum_integer'], 'Number'); } if (data.hasOwnProperty('enum_number')) { obj['enum_number'] = ApiClient.convertToType(data['enum_number'], 'Number'); @@ -118,7 +118,7 @@ /** * Allowed values for the enum_integer property. - * @enum {Integer} + * @enum {Number} * @readonly */ exports.EnumIntegerEnum = { diff --git a/samples/client/petstore/javascript/src/model/FormatTest.js b/samples/client/petstore/javascript/src/model/FormatTest.js index 4f6013f9d31..4f4c82f3e6b 100644 --- a/samples/client/petstore/javascript/src/model/FormatTest.js +++ b/samples/client/petstore/javascript/src/model/FormatTest.js @@ -87,13 +87,13 @@ obj = obj || new exports(); if (data.hasOwnProperty('integer')) { - obj['integer'] = ApiClient.convertToType(data['integer'], 'Integer'); + obj['integer'] = ApiClient.convertToType(data['integer'], 'Number'); } if (data.hasOwnProperty('int32')) { - obj['int32'] = ApiClient.convertToType(data['int32'], 'Integer'); + obj['int32'] = ApiClient.convertToType(data['int32'], 'Number'); } if (data.hasOwnProperty('int64')) { - obj['int64'] = ApiClient.convertToType(data['int64'], 'Integer'); + obj['int64'] = ApiClient.convertToType(data['int64'], 'Number'); } if (data.hasOwnProperty('number')) { obj['number'] = ApiClient.convertToType(data['number'], 'Number'); @@ -130,15 +130,15 @@ } /** - * @member {Integer} integer + * @member {Number} integer */ exports.prototype['integer'] = undefined; /** - * @member {Integer} int32 + * @member {Number} int32 */ exports.prototype['int32'] = undefined; /** - * @member {Integer} int64 + * @member {Number} int64 */ exports.prototype['int64'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/List.js b/samples/client/petstore/javascript/src/model/List.js new file mode 100644 index 00000000000..7e88e470df8 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/List.js @@ -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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.List = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The List model module. + * @module model/List + * @version 1.0.0 + */ + + /** + * Constructs a new List. + * @alias module:model/List + * @class + */ + var exports = function() { + var _this = this; + + + }; + + /** + * Constructs a List from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/List} obj Optional instance to populate. + * @return {module:model/List} The populated List instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('123-list')) { + obj['123-list'] = ApiClient.convertToType(data['123-list'], 'String'); + } + } + return obj; + } + + /** + * @member {String} 123-list + */ + exports.prototype['123-list'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/Model200Response.js b/samples/client/petstore/javascript/src/model/Model200Response.js index 671d6876a12..7e1b995e012 100644 --- a/samples/client/petstore/javascript/src/model/Model200Response.js +++ b/samples/client/petstore/javascript/src/model/Model200Response.js @@ -73,7 +73,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + obj['name'] = ApiClient.convertToType(data['name'], 'Number'); } if (data.hasOwnProperty('class')) { obj['class'] = ApiClient.convertToType(data['class'], 'String'); @@ -83,7 +83,7 @@ } /** - * @member {Integer} name + * @member {Number} name */ exports.prototype['name'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/ModelReturn.js b/samples/client/petstore/javascript/src/model/ModelReturn.js index 5358484fb21..ca81cd35998 100644 --- a/samples/client/petstore/javascript/src/model/ModelReturn.js +++ b/samples/client/petstore/javascript/src/model/ModelReturn.js @@ -72,14 +72,14 @@ obj = obj || new exports(); if (data.hasOwnProperty('return')) { - obj['return'] = ApiClient.convertToType(data['return'], 'Integer'); + obj['return'] = ApiClient.convertToType(data['return'], 'Number'); } } return obj; } /** - * @member {Integer} return + * @member {Number} return */ exports.prototype['return'] = undefined; diff --git a/samples/client/petstore/javascript/src/model/Name.js b/samples/client/petstore/javascript/src/model/Name.js index 8a50a92c49c..67d343c9af3 100644 --- a/samples/client/petstore/javascript/src/model/Name.js +++ b/samples/client/petstore/javascript/src/model/Name.js @@ -53,7 +53,7 @@ * Model for testing model name same as property name * @alias module:model/Name * @class - * @param name {Integer} + * @param name {Number} */ var exports = function(name) { var _this = this; @@ -76,27 +76,27 @@ obj = obj || new exports(); if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + obj['name'] = ApiClient.convertToType(data['name'], 'Number'); } if (data.hasOwnProperty('snake_case')) { - obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Integer'); + obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Number'); } if (data.hasOwnProperty('property')) { obj['property'] = ApiClient.convertToType(data['property'], 'String'); } if (data.hasOwnProperty('123Number')) { - obj['123Number'] = ApiClient.convertToType(data['123Number'], 'Integer'); + obj['123Number'] = ApiClient.convertToType(data['123Number'], 'Number'); } } return obj; } /** - * @member {Integer} name + * @member {Number} name */ exports.prototype['name'] = undefined; /** - * @member {Integer} snake_case + * @member {Number} snake_case */ exports.prototype['snake_case'] = undefined; /** @@ -104,7 +104,7 @@ */ exports.prototype['property'] = undefined; /** - * @member {Integer} 123Number + * @member {Number} 123Number */ exports.prototype['123Number'] = undefined; diff --git a/samples/client/petstore/javascript/src/model/Order.js b/samples/client/petstore/javascript/src/model/Order.js index f1cdab74f70..fbf719fd674 100644 --- a/samples/client/petstore/javascript/src/model/Order.js +++ b/samples/client/petstore/javascript/src/model/Order.js @@ -76,13 +76,13 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('petId')) { - obj['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); + obj['petId'] = ApiClient.convertToType(data['petId'], 'Number'); } if (data.hasOwnProperty('quantity')) { - obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); + obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Number'); } if (data.hasOwnProperty('shipDate')) { obj['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); @@ -98,15 +98,15 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** - * @member {Integer} petId + * @member {Number} petId */ exports.prototype['petId'] = undefined; /** - * @member {Integer} quantity + * @member {Number} quantity */ exports.prototype['quantity'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/Pet.js b/samples/client/petstore/javascript/src/model/Pet.js index 5575c2087d5..89fbb1d159f 100644 --- a/samples/client/petstore/javascript/src/model/Pet.js +++ b/samples/client/petstore/javascript/src/model/Pet.js @@ -78,7 +78,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('category')) { obj['category'] = Category.constructFromObject(data['category']); @@ -100,7 +100,7 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/SpecialModelName.js b/samples/client/petstore/javascript/src/model/SpecialModelName.js index b4e6e67ea8c..ec064be656b 100644 --- a/samples/client/petstore/javascript/src/model/SpecialModelName.js +++ b/samples/client/petstore/javascript/src/model/SpecialModelName.js @@ -71,14 +71,14 @@ obj = obj || new exports(); if (data.hasOwnProperty('$special[property.name]')) { - obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Integer'); + obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Number'); } } return obj; } /** - * @member {Integer} $special[property.name] + * @member {Number} $special[property.name] */ exports.prototype['$special[property.name]'] = undefined; diff --git a/samples/client/petstore/javascript/src/model/Tag.js b/samples/client/petstore/javascript/src/model/Tag.js index 010263babe3..bcf97c7bad0 100644 --- a/samples/client/petstore/javascript/src/model/Tag.js +++ b/samples/client/petstore/javascript/src/model/Tag.js @@ -72,7 +72,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); @@ -82,7 +82,7 @@ } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/User.js b/samples/client/petstore/javascript/src/model/User.js index 1c77bd4bb07..38a1bd1139d 100644 --- a/samples/client/petstore/javascript/src/model/User.js +++ b/samples/client/petstore/javascript/src/model/User.js @@ -78,7 +78,7 @@ obj = obj || new exports(); if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('username')) { obj['username'] = ApiClient.convertToType(data['username'], 'String'); @@ -99,14 +99,14 @@ obj['phone'] = ApiClient.convertToType(data['phone'], 'String'); } if (data.hasOwnProperty('userStatus')) { - obj['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); + obj['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Number'); } } return obj; } /** - * @member {Integer} id + * @member {Number} id */ exports.prototype['id'] = undefined; /** @@ -135,7 +135,7 @@ exports.prototype['phone'] = undefined; /** * User Status - * @member {Integer} userStatus + * @member {Number} userStatus */ exports.prototype['userStatus'] = undefined; diff --git a/samples/client/petstore/javascript/test/ApiClientTest.js b/samples/client/petstore/javascript/test/ApiClientTest.js index 3a8eb843d74..3a082774538 100644 --- a/samples/client/petstore/javascript/test/ApiClientTest.js +++ b/samples/client/petstore/javascript/test/ApiClientTest.js @@ -13,6 +13,7 @@ describe('ApiClient', function() { expect(apiClient.basePath).to.be('http://petstore.swagger.io/v2'); expect(apiClient.authentications).to.eql({ petstore_auth: {type: 'oauth2'}, + http_basic_test: {type: 'basic'}, api_key: {type: 'apiKey', 'in': 'header', name: 'api_key'} /* commented out the following as these fake security def (testing purpose) * has been removed from the spec, we'll add it back after updating the diff --git a/samples/client/petstore/javascript/test/model/Client.spec.js b/samples/client/petstore/javascript/test/model/Client.spec.js new file mode 100644 index 00000000000..7bba630a29c --- /dev/null +++ b/samples/client/petstore/javascript/test/model/Client.spec.js @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.Client(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Client', function() { + it('should create an instance of Client', function() { + // uncomment below and update the code to test Client + //var instane = new SwaggerPetstore.Client(); + //expect(instance).to.be.a(SwaggerPetstore.Client); + }); + + it('should have the property client (base name: "client")', function() { + // uncomment below and update the code to test the property client + //var instane = new SwaggerPetstore.Client(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/test/model/EnumArrays.spec.js b/samples/client/petstore/javascript/test/model/EnumArrays.spec.js new file mode 100644 index 00000000000..2d26fb9920f --- /dev/null +++ b/samples/client/petstore/javascript/test/model/EnumArrays.spec.js @@ -0,0 +1,82 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.EnumArrays(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('EnumArrays', function() { + it('should create an instance of EnumArrays', function() { + // uncomment below and update the code to test EnumArrays + //var instane = new SwaggerPetstore.EnumArrays(); + //expect(instance).to.be.a(SwaggerPetstore.EnumArrays); + }); + + it('should have the property justSymbol (base name: "just_symbol")', function() { + // uncomment below and update the code to test the property justSymbol + //var instane = new SwaggerPetstore.EnumArrays(); + //expect(instance).to.be(); + }); + + it('should have the property arrayEnum (base name: "array_enum")', function() { + // uncomment below and update the code to test the property arrayEnum + //var instane = new SwaggerPetstore.EnumArrays(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/test/model/List.spec.js b/samples/client/petstore/javascript/test/model/List.spec.js new file mode 100644 index 00000000000..e73583f9ebc --- /dev/null +++ b/samples/client/petstore/javascript/test/model/List.spec.js @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.List(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('List', function() { + it('should create an instance of List', function() { + // uncomment below and update the code to test List + //var instane = new SwaggerPetstore.List(); + //expect(instance).to.be.a(SwaggerPetstore.List); + }); + + it('should have the property _123List (base name: "123-list")', function() { + // uncomment below and update the code to test the property _123List + //var instane = new SwaggerPetstore.List(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/jmeter/.swagger-codegen-ignore b/samples/client/petstore/jmeter/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/jmeter/.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/jmeter/LICENSE b/samples/client/petstore/jmeter/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/jmeter/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/jmeter/PetApi.csv b/samples/client/petstore/jmeter/PetApi.csv new file mode 100644 index 00000000000..29b09a1715d --- /dev/null +++ b/samples/client/petstore/jmeter/PetApi.csv @@ -0,0 +1,2 @@ +testCase,httpStatusCode,body,petId,apiKey,status,tags,petId,body,petId,name,status,petId,additionalMetadata,file +Success,200,0,0,0,0,0,0,0,0,0,0,0,0,0 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/PetApi.jmx b/samples/client/petstore/jmeter/PetApi.jmx new file mode 100644 index 00000000000..c61a96b600e --- /dev/null +++ b/samples/client/petstore/jmeter/PetApi.jmx @@ -0,0 +1,673 @@ + + + + + + false + false + + + + host + localhost + = + + + port + 8080 + = + + + + + + + + + + testCases + ${__P(testCases,10)} + = + + + host + ${__P(host,localhost)} + = + + + port + ${__P(port,8080)} + = + + + testData.addPetFile + ${__P(testData.addPetFile,PetApi.csv)} + = + + + testData.deletePetFile + ${__P(testData.deletePetFile,PetApi.csv)} + = + + + testData.findPetsByStatusFile + ${__P(testData.findPetsByStatusFile,PetApi.csv)} + = + + + testData.findPetsByTagsFile + ${__P(testData.findPetsByTagsFile,PetApi.csv)} + = + + + testData.getPetByIdFile + ${__P(testData.getPetByIdFile,PetApi.csv)} + = + + + testData.updatePetFile + ${__P(testData.updatePetFile,PetApi.csv)} + = + + + testData.updatePetWithFormFile + ${__P(testData.updatePetWithFormFile,PetApi.csv)} + = + + + testData.uploadFileFile + ${__P(testData.uploadFileFile,PetApi.csv)} + = + + + + + + + + + ${host} + ${port} + + + + + + 4 + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/pet + POST + true + false + true + false + HttpClient3.1 + false + + Add a new pet to the store + + + + , + + ${testData.addPetFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + apiKey + ${__RandomString(10,qwertyuiopasdfghjklzxcvbnm)} + + + + + + + + + + + + + + + + /v2/pet/${petId} + DELETE + true + false + true + false + HttpClient3.1 + false + + Deletes a pet + + + + , + + ${testData.deletePetFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + false + ${status} + = + true + status + + + + + + + + + + /v2/pet/findByStatus + GET + true + false + true + false + HttpClient3.1 + false + + Finds Pets by status Multiple status values can be provided with comma separated strings + + + + , + + ${testData.findPetsByStatusFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + false + ${tags} + = + true + tags + + + + + + + + + + /v2/pet/findByTags + GET + true + false + true + false + HttpClient3.1 + false + + Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + + + + , + + ${testData.findPetsByTagsFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/pet/${petId} + GET + true + false + true + false + HttpClient3.1 + false + + Find pet by ID Returns a single pet + + + + , + + ${testData.getPetByIdFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/pet + PUT + true + false + true + false + HttpClient3.1 + false + + Update an existing pet + + + + , + + ${testData.updatePetFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/pet/${petId} + POST + true + false + true + false + HttpClient3.1 + false + + Updates a pet in the store with form data + + + + , + + ${testData.updatePetWithFormFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/pet/${petId}/uploadImage + POST + true + false + true + false + HttpClient3.1 + false + + uploads an image + + + + , + + ${testData.uploadFileFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + true + + + + + + + + diff --git a/samples/client/petstore/jmeter/StoreApi.csv b/samples/client/petstore/jmeter/StoreApi.csv new file mode 100644 index 00000000000..70fd54e2b20 --- /dev/null +++ b/samples/client/petstore/jmeter/StoreApi.csv @@ -0,0 +1,2 @@ +testCase,httpStatusCode,orderId,orderId,body +Success,200,0,0,0 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/StoreApi.jmx b/samples/client/petstore/jmeter/StoreApi.jmx new file mode 100644 index 00000000000..07003622bba --- /dev/null +++ b/samples/client/petstore/jmeter/StoreApi.jmx @@ -0,0 +1,375 @@ + + + + + + false + false + + + + host + localhost + = + + + port + 8080 + = + + + + + + + + + + testCases + ${__P(testCases,10)} + = + + + host + ${__P(host,localhost)} + = + + + port + ${__P(port,8080)} + = + + + testData.deleteOrderFile + ${__P(testData.deleteOrderFile,StoreApi.csv)} + = + + + testData.getInventoryFile + ${__P(testData.getInventoryFile,StoreApi.csv)} + = + + + testData.getOrderByIdFile + ${__P(testData.getOrderByIdFile,StoreApi.csv)} + = + + + testData.placeOrderFile + ${__P(testData.placeOrderFile,StoreApi.csv)} + = + + + + + + + + + ${host} + ${port} + + + + + + 4 + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/store/order/${orderId} + DELETE + true + false + true + false + HttpClient3.1 + false + + Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + + + , + + ${testData.deleteOrderFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/store/inventory + GET + true + false + true + false + HttpClient3.1 + false + + Returns pet inventories by status Returns a map of status codes to quantities + + + + , + + ${testData.getInventoryFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/store/order/${orderId} + GET + true + false + true + false + HttpClient3.1 + false + + Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + + + , + + ${testData.getOrderByIdFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/store/order + POST + true + false + true + false + HttpClient3.1 + false + + Place an order for a pet + + + + , + + ${testData.placeOrderFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + true + + + + + + + + diff --git a/samples/client/petstore/jmeter/UserApi.csv b/samples/client/petstore/jmeter/UserApi.csv new file mode 100644 index 00000000000..92242d4077c --- /dev/null +++ b/samples/client/petstore/jmeter/UserApi.csv @@ -0,0 +1,2 @@ +testCase,httpStatusCode,body,body,body,username,username,username,password,username,body +Success,200,0,0,0,0,0,0,0,0,0 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/UserApi.jmx b/samples/client/petstore/jmeter/UserApi.jmx new file mode 100644 index 00000000000..5375a419a05 --- /dev/null +++ b/samples/client/petstore/jmeter/UserApi.jmx @@ -0,0 +1,669 @@ + + + + + + false + false + + + + host + localhost + = + + + port + 8080 + = + + + + + + + + + + testCases + ${__P(testCases,10)} + = + + + host + ${__P(host,localhost)} + = + + + port + ${__P(port,8080)} + = + + + testData.createUserFile + ${__P(testData.createUserFile,UserApi.csv)} + = + + + testData.createUsersWithArrayInputFile + ${__P(testData.createUsersWithArrayInputFile,UserApi.csv)} + = + + + testData.createUsersWithListInputFile + ${__P(testData.createUsersWithListInputFile,UserApi.csv)} + = + + + testData.deleteUserFile + ${__P(testData.deleteUserFile,UserApi.csv)} + = + + + testData.getUserByNameFile + ${__P(testData.getUserByNameFile,UserApi.csv)} + = + + + testData.loginUserFile + ${__P(testData.loginUserFile,UserApi.csv)} + = + + + testData.logoutUserFile + ${__P(testData.logoutUserFile,UserApi.csv)} + = + + + testData.updateUserFile + ${__P(testData.updateUserFile,UserApi.csv)} + = + + + + + + + + + ${host} + ${port} + + + + + + 4 + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user + POST + true + false + true + false + HttpClient3.1 + false + + Create user This can only be done by the logged in user. + + + + , + + ${testData.createUserFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user/createWithArray + POST + true + false + true + false + HttpClient3.1 + false + + Creates list of users with given input array + + + + , + + ${testData.createUsersWithArrayInputFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user/createWithList + POST + true + false + true + false + HttpClient3.1 + false + + Creates list of users with given input array + + + + , + + ${testData.createUsersWithListInputFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user/${username} + DELETE + true + false + true + false + HttpClient3.1 + false + + Delete user This can only be done by the logged in user. + + + + , + + ${testData.deleteUserFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user/${username} + GET + true + false + true + false + HttpClient3.1 + false + + Get user by user name + + + + , + + ${testData.getUserByNameFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + false + ${username} + = + true + username + + + false + ${password} + = + true + password + + + + + + + + + + /v2/user/login + GET + true + false + true + false + HttpClient3.1 + false + + Logs user into the system + + + + , + + ${testData.loginUserFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user/logout + GET + true + false + true + false + HttpClient3.1 + false + + Logs out current logged in user session + + + + , + + ${testData.logoutUserFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + + + + + + + + + + + + + + + + /v2/user/${username} + PUT + true + false + true + false + HttpClient3.1 + false + + Updated user This can only be done by the logged in user. + + + + , + + ${testData.updateUserFile} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + true + + + + + + + + diff --git a/samples/client/petstore/objc/core-data/.swagger-codegen-ignore b/samples/client/petstore/objc/core-data/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/objc/core-data/.swagger-codegen-ignore +++ b/samples/client/petstore/objc/core-data/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/objc/core-data/README.md b/samples/client/petstore/objc/core-data/README.md index 151ffe96225..20e27d6fa0a 100644 --- a/samples/client/petstore/objc/core-data/README.md +++ b/samples/client/petstore/objc/core-data/README.md @@ -6,7 +6,6 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-06-16T11:33:34.619+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -56,7 +55,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. ## Getting Started @@ -74,9 +73,9 @@ SWGPet* *body = [[SWGPet alloc] init]; // Pet object that needs to be added to t SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; - // Add a new pet to the store +// Add a new pet to the store [apiInstance addPetWithBody:body - completionHandler: ^(NSError* error)) { + completionHandler: ^(NSError* error) { if (error) { NSLog(@"Error: %@", error); } @@ -124,6 +123,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -133,12 +138,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h index 97f914a627e..6c3303848f8 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h @@ -61,7 +61,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// @@ -74,7 +74,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index 409f5b86655..16d1541471b 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -208,7 +208,7 @@ -(NSNumber*) deletePetWithPetId: (NSNumber*) petId /// /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// @param status Status values that need to be considered for filter (optional, default to available) /// /// @returns NSArray* @@ -270,7 +270,7 @@ -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status /// /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @param tags Tags to filter by (optional) /// /// @returns NSArray* diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h index 2ec5c9b0fcc..a5f267821d8 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h @@ -154,7 +154,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m index 24172638bba..b21290068a1 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m @@ -110,13 +110,6 @@ - (NSDictionary *) apiKeyPrefix { - (NSDictionary *) authSettings { return @{ - @"petstore_auth": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, @"api_key": @{ @"type": @"api_key", @@ -124,6 +117,13 @@ - (NSDictionary *) authSettings { @"key": @"api_key", @"value": [self getApiKeyWithPrefix:@"api_key"] }, + @"petstore_auth": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, }; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m index a0efd1d5927..6ac9f75e818 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m @@ -223,7 +223,7 @@ -(NSError *)emptyValueOccurredError { } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index b69c907b161..68c3e696436 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -214,12 +214,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */; buildPhases = ( - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */, + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */, 6003F586195388D20070C39A /* Sources */, 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */, - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */, + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -234,12 +234,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */; buildPhases = ( - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */, + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */, 6003F5AA195388D20070C39A /* Sources */, 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */, - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */, + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -303,14 +303,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */ = { + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -318,14 +318,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */ = { + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -333,14 +333,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */ = { + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -348,14 +348,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */ = { + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -363,14 +363,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */ = { + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -378,14 +378,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */ = { + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/default/.swagger-codegen-ignore b/samples/client/petstore/objc/default/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/objc/default/.swagger-codegen-ignore +++ b/samples/client/petstore/objc/default/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index c27432d29cc..20e27d6fa0a 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,6 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-06-16T11:33:30.448+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -56,7 +55,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. ## Getting Started @@ -74,9 +73,9 @@ SWGPet* *body = [[SWGPet alloc] init]; // Pet object that needs to be added to t SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; - // Add a new pet to the store +// Add a new pet to the store [apiInstance addPetWithBody:body - completionHandler: ^(NSError* error)) { + completionHandler: ^(NSError* error) { if (error) { NSLog(@"Error: %@", error); } @@ -124,6 +123,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -133,12 +138,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h index 97f914a627e..6c3303848f8 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h @@ -61,7 +61,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// @@ -74,7 +74,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index 409f5b86655..16d1541471b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -208,7 +208,7 @@ -(NSNumber*) deletePetWithPetId: (NSNumber*) petId /// /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// @param status Status values that need to be considered for filter (optional, default to available) /// /// @returns NSArray* @@ -270,7 +270,7 @@ -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status /// /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @param tags Tags to filter by (optional) /// /// @returns NSArray* diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h index 2ec5c9b0fcc..a5f267821d8 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h @@ -154,7 +154,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m index 24172638bba..b21290068a1 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m @@ -110,13 +110,6 @@ - (NSDictionary *) apiKeyPrefix { - (NSDictionary *) authSettings { return @{ - @"petstore_auth": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, @"api_key": @{ @"type": @"api_key", @@ -124,6 +117,13 @@ - (NSDictionary *) authSettings { @"key": @"api_key", @"value": [self getApiKeyWithPrefix:@"api_key"] }, + @"petstore_auth": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, }; } diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m index a0efd1d5927..6ac9f75e818 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m @@ -223,7 +223,7 @@ -(NSError *)emptyValueOccurredError { } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index cd20eb43998..25e7b5a2d2c 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -232,12 +232,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */; buildPhases = ( - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */, + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */, 6003F586195388D20070C39A /* Sources */, 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */, - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */, + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -252,12 +252,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */; buildPhases = ( - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */, + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */, 6003F5AA195388D20070C39A /* Sources */, 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */, - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */, + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -321,14 +321,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */ = { + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -336,14 +336,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */ = { + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -351,14 +351,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */ = { + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -366,14 +366,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */ = { + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -381,14 +381,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */ = { + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -396,14 +396,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */ = { + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index d702c353855..27674ded241 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -130,7 +130,7 @@ void (empty response body) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```objc @@ -185,7 +185,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```objc diff --git a/samples/client/petstore/perl/.swagger-codegen-ignore b/samples/client/petstore/perl/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/perl/.swagger-codegen-ignore +++ b/samples/client/petstore/perl/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 3c7a28082e6..134da972c30 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -10,7 +10,7 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-28T16:35:21.686+08:00 +- Build date: 2016-08-28T17:02:32.695+03:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen ## A note on Moose @@ -241,11 +241,14 @@ use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::Client; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumArrays; use WWW::SwaggerClient::Object::EnumClass; use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; use WWW::SwaggerClient::Object::HasOnlyReadOnly; +use WWW::SwaggerClient::Object::List; use WWW::SwaggerClient::Object::MapTest; use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; @@ -284,11 +287,14 @@ use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::Client; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumArrays; use WWW::SwaggerClient::Object::EnumClass; use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; use WWW::SwaggerClient::Object::HasOnlyReadOnly; +use WWW::SwaggerClient::Object::List; use WWW::SwaggerClient::Object::MapTest; use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; @@ -304,15 +310,18 @@ use WWW::SwaggerClient::Object::User; # for displaying the API response data use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::; my $api_instance = WWW::SwaggerClient::FakeApi->new(); -my $test code inject */ =end = 'test code inject */ =end_example'; # string | To test code injection */ +my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - $api_instance->test_code_inject__end(test code inject */ =end => $test code inject */ =end); + my $result = $api_instance->test_client_model(body => $body); + print Dumper($result); }; if ($@) { - warn "Exception when calling FakeApi->test_code_inject__end: $@\n"; + warn "Exception when calling FakeApi->test_client_model: $@\n"; } ``` @@ -323,9 +332,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**test_code_inject__end**](docs/FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ +*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_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -358,11 +367,14 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::ArrayTest](docs/ArrayTest.md) - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - [WWW::SwaggerClient::Object::Category](docs/Category.md) + - [WWW::SwaggerClient::Object::Client](docs/Client.md) - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) + - [WWW::SwaggerClient::Object::EnumArrays](docs/EnumArrays.md) - [WWW::SwaggerClient::Object::EnumClass](docs/EnumClass.md) - [WWW::SwaggerClient::Object::EnumTest](docs/EnumTest.md) - [WWW::SwaggerClient::Object::FormatTest](docs/FormatTest.md) - [WWW::SwaggerClient::Object::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [WWW::SwaggerClient::Object::List](docs/List.md) - [WWW::SwaggerClient::Object::MapTest](docs/MapTest.md) - [WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [WWW::SwaggerClient::Object::Model200Response](docs/Model200Response.md) @@ -377,7 +389,7 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::User](docs/User.md) -# DOCUMENTATION FOR AUTHORIATION +# DOCUMENTATION FOR AUTHORIZATION ## api_key @@ -394,5 +406,9 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## http_basic_test + +- **Type**: HTTP basic authentication + diff --git a/samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..aa02dc37dbb --- /dev/null +++ b/samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_array_number** | **ARRAY[ARRAY[Number]]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/ArrayOfNumberOnly.md b/samples/client/petstore/perl/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..326b28c8afe --- /dev/null +++ b/samples/client/petstore/perl/docs/ArrayOfNumberOnly.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::ArrayOfNumberOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ArrayOfNumberOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_number** | [**ARRAY[Number]**](Number.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/ArrayTest.md b/samples/client/petstore/perl/docs/ArrayTest.md index e6495d4da5e..635c26a893a 100644 --- a/samples/client/petstore/perl/docs/ArrayTest.md +++ b/samples/client/petstore/perl/docs/ArrayTest.md @@ -11,7 +11,6 @@ Name | Type | Description | Notes **array_of_string** | **ARRAY[string]** | | [optional] **array_array_of_integer** | **ARRAY[ARRAY[int]]** | | [optional] **array_array_of_model** | **ARRAY[ARRAY[ReadOnlyFirst]]** | | [optional] -**array_of_enum** | **ARRAY[string]** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/docs/Client.md b/samples/client/petstore/perl/docs/Client.md new file mode 100644 index 00000000000..08f3b74f010 --- /dev/null +++ b/samples/client/petstore/perl/docs/Client.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::Client + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Client; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/EnumArrays.md b/samples/client/petstore/perl/docs/EnumArrays.md new file mode 100644 index 00000000000..b693b9a2641 --- /dev/null +++ b/samples/client/petstore/perl/docs/EnumArrays.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::EnumArrays + +## Load the model package +```perl +use WWW::SwaggerClient::Object::EnumArrays; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **string** | | [optional] +**array_enum** | **ARRAY[string]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index 1207308ca23..985b78596e2 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -9,28 +9,31 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject__end**](FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ +[**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_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -# **test_code_inject__end** -> test_code_inject__end(test code inject */ =end => $test code inject */ =end) +# **test_client_model** +> Client test_client_model(body => $body) -To test code injection */ +To test \"client\" model ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new(); -my $test code inject */ =end = 'test code inject */ =end_example'; # string | To test code injection */ +my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - $api_instance->test_code_inject__end(test code inject */ =end => $test code inject */ =end); + my $result = $api_instance->test_client_model(body => $body); + print Dumper($result); }; if ($@) { - warn "Exception when calling FakeApi->test_code_inject__end: $@\n"; + warn "Exception when calling FakeApi->test_client_model: $@\n"; } ``` @@ -38,11 +41,11 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test code inject */ =end** | **string**| To test code injection */ | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -void (empty response body) +[**Client**](Client.md) ### Authorization @@ -50,13 +53,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **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) # **test_endpoint_parameters** -> test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password) +> test_endpoint_parameters(number => $number, double => $double, pattern_without_delimiter => $pattern_without_delimiter, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, string => $string, binary => $binary, date => $date, date_time => $date_time, password => $password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -65,23 +68,30 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::FakeApi; + +# Configure HTTP basic authorization: http_basic_test +$WWW::SwaggerClient::Configuration::username = 'YOUR_USERNAME'; +$WWW::SwaggerClient::Configuration::password = 'YOUR_PASSWORD'; my $api_instance = WWW::SwaggerClient::FakeApi->new(); my $number = 3.4; # Number | None my $double = 1.2; # double | None -my $string = 'string_example'; # string | None +my $pattern_without_delimiter = 'pattern_without_delimiter_example'; # string | None my $byte = 'B'; # string | None my $integer = 56; # int | None my $int32 = 56; # int | None my $int64 = 789; # int | None my $float = 3.4; # double | None +my $string = 'string_example'; # string | None my $binary = 'B'; # string | None my $date = DateTime->from_epoch(epoch => str2time('2013-10-20')); # DateTime | None my $date_time = DateTime->from_epoch(epoch => str2time('2013-10-20T19:20:30+01:00')); # DateTime | None my $password = 'password_example'; # string | None eval { - $api_instance->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); + $api_instance->test_endpoint_parameters(number => $number, double => $double, pattern_without_delimiter => $pattern_without_delimiter, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, string => $string, binary => $binary, date => $date, date_time => $date_time, password => $password); }; if ($@) { warn "Exception when calling FakeApi->test_endpoint_parameters: $@\n"; @@ -94,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **Number**| None | **double** | **double**| None | - **string** | **string**| None | + **pattern_without_delimiter** | **string**| None | **byte** | **string**| None | **integer** | **int**| None | [optional] **int32** | **int**| None | [optional] **int64** | **int**| None | [optional] **float** | **double**| None | [optional] + **string** | **string**| None | [optional] **binary** | **string**| None | [optional] **date** | **DateTime**| None | [optional] **date_time** | **DateTime**| None | [optional] @@ -111,7 +122,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -120,25 +131,32 @@ 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_enum_query_parameters** -> test_enum_query_parameters(enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double) +# **test_enum_parameters** +> test_enum_parameters(enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string, enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double) -To test enum query parameters +To test enum parameters ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new(); +my $enum_form_string_array = []; # ARRAY[string] | Form parameter enum test (string array) +my $enum_form_string = 'enum_form_string_example'; # string | Form parameter enum test (string) +my $enum_header_string_array = []; # ARRAY[string] | Header parameter enum test (string array) +my $enum_header_string = 'enum_header_string_example'; # string | Header parameter enum test (string) +my $enum_query_string_array = []; # ARRAY[string] | Query parameter enum test (string array) my $enum_query_string = 'enum_query_string_example'; # string | Query parameter enum test (string) my $enum_query_integer = 3.4; # Number | Query parameter enum test (double) my $enum_query_double = 1.2; # double | Query parameter enum test (double) eval { - $api_instance->test_enum_query_parameters(enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double); + $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); }; if ($@) { - warn "Exception when calling FakeApi->test_enum_query_parameters: $@\n"; + warn "Exception when calling FakeApi->test_enum_parameters: $@\n"; } ``` @@ -146,6 +164,11 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**ARRAY[string]**](string.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**ARRAY[string]**](string.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**ARRAY[string]**](string.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **Number**| Query parameter enum test (double) | [optional] **enum_query_double** | **double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/perl/docs/HasOnlyReadOnly.md b/samples/client/petstore/perl/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..04b609cb12b --- /dev/null +++ b/samples/client/petstore/perl/docs/HasOnlyReadOnly.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::HasOnlyReadOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/docs/List.md b/samples/client/petstore/perl/docs/List.md new file mode 100644 index 00000000000..ea7bbed15a2 --- /dev/null +++ b/samples/client/petstore/perl/docs/List.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::List + +## Load the model package +```perl +use WWW::SwaggerClient::Object::List; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/MapTest.md b/samples/client/petstore/perl/docs/MapTest.md new file mode 100644 index 00000000000..8105d4d8756 --- /dev/null +++ b/samples/client/petstore/perl/docs/MapTest.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::MapTest + +## Load the model package +```perl +use WWW::SwaggerClient::Object::MapTest; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_map_of_string** | **HASH[string,HASH[string,string]]** | | [optional] +**map_of_enum_string** | **HASH[string,string]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/NumberOnly.md b/samples/client/petstore/perl/docs/NumberOnly.md new file mode 100644 index 00000000000..068017e8fb6 --- /dev/null +++ b/samples/client/petstore/perl/docs/NumberOnly.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::NumberOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::NumberOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_number** | [**Number**](Number.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md index c2f4e2ce4ee..ab07b6413a2 100644 --- a/samples/client/petstore/perl/docs/PetApi.md +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -29,6 +29,8 @@ Add a new pet to the store ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -75,6 +77,8 @@ Deletes a pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -123,12 +127,14 @@ Multiple status values can be provided with comma separated strings ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $status = (); # ARRAY[string] | Status values that need to be considered for filter +my $status = []; # ARRAY[string] | Status values that need to be considered for filter eval { my $result = $api_instance->find_pets_by_status(status => $status); @@ -170,12 +176,14 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $tags = (); # ARRAY[string] | Tags to filter by +my $tags = []; # ARRAY[string] | Tags to filter by eval { my $result = $api_instance->find_pets_by_tags(tags => $tags); @@ -217,6 +225,8 @@ Returns a single pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; @@ -266,6 +276,8 @@ Update an existing pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -312,6 +324,8 @@ Updates a pet in the store with form data ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -362,6 +376,8 @@ uploads an image ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; diff --git a/samples/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md index f0681b47167..d57b4121cc0 100644 --- a/samples/client/petstore/perl/docs/StoreApi.md +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -25,6 +25,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $order_id = 'order_id_example'; # string | ID of the order that needs to be deleted @@ -68,6 +70,8 @@ Returns a map of status codes to quantities ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; @@ -113,6 +117,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $order_id = 789; # int | ID of pet that needs to be fetched @@ -157,6 +163,8 @@ Place an order for a pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet diff --git a/samples/client/petstore/perl/docs/UserApi.md b/samples/client/petstore/perl/docs/UserApi.md index faa4c799739..081f0dc1d55 100644 --- a/samples/client/petstore/perl/docs/UserApi.md +++ b/samples/client/petstore/perl/docs/UserApi.md @@ -29,6 +29,8 @@ This can only be done by the logged in user. ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $body = WWW::SwaggerClient::Object::User->new(); # User | Created user object @@ -72,9 +74,11 @@ Creates list of users with given input array ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); -my $body = (WWW::SwaggerClient::Object::ARRAY[User]->new()); # ARRAY[User] | List of user object +my $body = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object eval { $api_instance->create_users_with_array_input(body => $body); @@ -115,9 +119,11 @@ Creates list of users with given input array ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); -my $body = (WWW::SwaggerClient::Object::ARRAY[User]->new()); # ARRAY[User] | List of user object +my $body = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object eval { $api_instance->create_users_with_list_input(body => $body); @@ -158,6 +164,8 @@ This can only be done by the logged in user. ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | The name that needs to be deleted @@ -201,6 +209,8 @@ Get user by user name ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | The name that needs to be fetched. Use user1 for testing. @@ -245,6 +255,8 @@ Logs user into the system ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | The user name for login @@ -291,6 +303,8 @@ Logs out current logged in user session ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); @@ -330,6 +344,8 @@ This can only be done by the logged in user. ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | name that need to be deleted diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 92228e6c747..ad679c64cb7 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -363,6 +363,12 @@ elsif ($auth eq 'petstore_auth') { $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; } } +elsif ($auth eq 'http_basic_test') { + + if ($WWW::SwaggerClient::Configuration::username || $WWW::SwaggerClient::Configuration::password) { + $header_params->{'Authorization'} = 'Basic ' . encode_base64($WWW::SwaggerClient::Configuration::username . ":" . $WWW::SwaggerClient::Configuration::password); + } + } else { # TODO show warning about security definition not found } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index d6f50b46251..f5489e038b1 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -42,9 +42,9 @@ use constant VERSION => '1.0.0'; # class/static variables our $http_timeout = 180; -our $http_user_agent = 'Perl-Swagger'; +our $http_user_agent = 'Swagger-Codegen/1.0.0/perl'; -# authenticaiton setting +# authentication setting our $api_key = {}; our $api_key_prefix = {}; our $api_key_in = {}; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm index eefd2641288..ef2ba24f88a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm @@ -64,60 +64,69 @@ sub new { # -# test_code_inject__end +# test_client_model # -# To test code injection */ +# To test \"client\" model # -# @param string $test code inject */ =end To test code injection */ (optional) +# @param Client $body client model (required) { my $params = { - 'test code inject */ =end' => { - data_type => 'string', - description => 'To test code injection */ ', - required => '0', + 'body' => { + data_type => 'Client', + description => 'client model', + required => '1', }, }; - __PACKAGE__->method_documentation->{ 'test_code_inject__end' } = { - summary => 'To test code injection */ ', + __PACKAGE__->method_documentation->{ 'test_client_model' } = { + summary => 'To test \"client\" model', params => $params, - returns => undef, + returns => 'Client', }; } -# @return void +# @return Client # -sub test_code_inject__end { +sub test_client_model { my ($self, %args) = @_; + # verify the required parameter 'body' is set + unless (exists $args{'body'}) { + croak("Missing the required parameter 'body' when calling test_client_model"); + } + # parse inputs my $_resource_path = '/fake'; $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'PUT'; + my $_method = 'PATCH'; my $query_params = {}; my $header_params = {}; my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', '*/ end'); + my $_header_accept = $self->{api_client}->select_header_accept('application/json'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', '*/ =end));(phpinfo('); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); - # form params - if ( exists $args{'test code inject */ =end'} ) { - $form_params->{'test code inject */ =end'} = $self->{api_client}->to_form_value($args{'test code inject */ =end'}); - } - my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + # authentication setting, if any my $auth_settings = [qw()]; # make the API Call - $self->{api_client}->call_api($_resource_path, $_method, + my $response = $self->{api_client}->call_api($_resource_path, $_method, $query_params, $form_params, $header_params, $_body_data, $auth_settings); - return; + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('Client', $response); + return $_response_object; } # @@ -127,12 +136,13 @@ sub test_code_inject__end { # # @param Number $number None (required) # @param double $double None (required) -# @param string $string None (required) +# @param string $pattern_without_delimiter None (required) # @param string $byte None (required) # @param int $integer None (optional) # @param int $int32 None (optional) # @param int $int64 None (optional) # @param double $float None (optional) +# @param string $string None (optional) # @param string $binary None (optional) # @param DateTime $date None (optional) # @param DateTime $date_time None (optional) @@ -149,7 +159,7 @@ sub test_code_inject__end { description => 'None', required => '1', }, - 'string' => { + 'pattern_without_delimiter' => { data_type => 'string', description => 'None', required => '1', @@ -179,6 +189,11 @@ sub test_code_inject__end { description => 'None', required => '0', }, + 'string' => { + data_type => 'string', + description => 'None', + required => '0', + }, 'binary' => { data_type => 'string', description => 'None', @@ -221,9 +236,9 @@ sub test_endpoint_parameters { croak("Missing the required parameter 'double' when calling test_endpoint_parameters"); } - # verify the required parameter 'string' is set - unless (exists $args{'string'}) { - croak("Missing the required parameter 'string' when calling test_endpoint_parameters"); + # verify the required parameter 'pattern_without_delimiter' is set + unless (exists $args{'pattern_without_delimiter'}) { + croak("Missing the required parameter 'pattern_without_delimiter' when calling test_endpoint_parameters"); } # verify the required parameter 'byte' is set @@ -282,6 +297,11 @@ sub test_endpoint_parameters { $form_params->{'string'} = $self->{api_client}->to_form_value($args{'string'}); } + # form params + if ( exists $args{'pattern_without_delimiter'} ) { + $form_params->{'pattern_without_delimiter'} = $self->{api_client}->to_form_value($args{'pattern_without_delimiter'}); + } + # form params if ( exists $args{'byte'} ) { $form_params->{'byte'} = $self->{api_client}->to_form_value($args{'byte'}); @@ -309,7 +329,7 @@ sub test_endpoint_parameters { my $_body_data; # authentication setting, if any - my $auth_settings = [qw()]; + my $auth_settings = [qw(http_basic_test )]; # make the API Call $self->{api_client}->call_api($_resource_path, $_method, @@ -319,15 +339,45 @@ sub test_endpoint_parameters { } # -# test_enum_query_parameters +# test_enum_parameters # -# To test enum query parameters +# To test enum parameters # +# @param ARRAY[string] $enum_form_string_array Form parameter enum test (string array) (optional) +# @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) +# @param ARRAY[string] $enum_header_string_array Header parameter enum test (string array) (optional) +# @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) +# @param ARRAY[string] $enum_query_string_array Query parameter enum test (string array) (optional) # @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) # @param Number $enum_query_integer Query parameter enum test (double) (optional) # @param double $enum_query_double Query parameter enum test (double) (optional) { my $params = { + 'enum_form_string_array' => { + data_type => 'ARRAY[string]', + description => 'Form parameter enum test (string array)', + required => '0', + }, + 'enum_form_string' => { + data_type => 'string', + description => 'Form parameter enum test (string)', + required => '0', + }, + 'enum_header_string_array' => { + data_type => 'ARRAY[string]', + description => 'Header parameter enum test (string array)', + required => '0', + }, + 'enum_header_string' => { + data_type => 'string', + description => 'Header parameter enum test (string)', + required => '0', + }, + 'enum_query_string_array' => { + data_type => 'ARRAY[string]', + description => 'Query parameter enum test (string array)', + required => '0', + }, 'enum_query_string' => { data_type => 'string', description => 'Query parameter enum test (string)', @@ -344,15 +394,15 @@ sub test_endpoint_parameters { required => '0', }, }; - __PACKAGE__->method_documentation->{ 'test_enum_query_parameters' } = { - summary => 'To test enum query parameters', + __PACKAGE__->method_documentation->{ 'test_enum_parameters' } = { + summary => 'To test enum parameters', params => $params, returns => undef, }; } # @return void # -sub test_enum_query_parameters { +sub test_enum_parameters { my ($self, %args) = @_; # parse inputs @@ -371,14 +421,39 @@ sub test_enum_query_parameters { } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); + # query params + if ( exists $args{'enum_query_string_array'}) { + $query_params->{'enum_query_string_array'} = $self->{api_client}->to_query_value($args{'enum_query_string_array'}); + } + + # query params + if ( exists $args{'enum_query_string'}) { + $query_params->{'enum_query_string'} = $self->{api_client}->to_query_value($args{'enum_query_string'}); + } + # query params if ( exists $args{'enum_query_integer'}) { $query_params->{'enum_query_integer'} = $self->{api_client}->to_query_value($args{'enum_query_integer'}); } + # header params + if ( exists $args{'enum_header_string_array'}) { + $header_params->{'enum_header_string_array'} = $self->{api_client}->to_header_value($args{'enum_header_string_array'}); + } + + # header params + if ( exists $args{'enum_header_string'}) { + $header_params->{'enum_header_string'} = $self->{api_client}->to_header_value($args{'enum_header_string'}); + } + + # form params + if ( exists $args{'enum_form_string_array'} ) { + $form_params->{'enum_form_string_array'} = $self->{api_client}->to_form_value($args{'enum_form_string_array'}); + } + # form params - if ( exists $args{'enum_query_string'} ) { - $form_params->{'enum_query_string'} = $self->{api_client}->to_form_value($args{'enum_query_string'}); + if ( exists $args{'enum_form_string'} ) { + $form_params->{'enum_form_string'} = $self->{api_client}->to_form_value($args{'enum_form_string'}); } # form params diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm new file mode 100644 index 00000000000..5d2a2f5e575 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'ArrayOfArrayOfNumberOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'array_array_number' => { + datatype => 'ARRAY[ARRAY[Number]]', + base_name => 'ArrayArrayNumber', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'array_array_number' => 'ARRAY[ARRAY[Number]]' +} ); + +__PACKAGE__->attribute_map( { + 'array_array_number' => 'ArrayArrayNumber' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm new file mode 100644 index 00000000000..4f3dbc51ece --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ArrayOfNumberOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'ArrayOfNumberOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'array_number' => { + datatype => 'ARRAY[Number]', + base_name => 'ArrayNumber', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'array_number' => 'ARRAY[Number]' +} ); + +__PACKAGE__->attribute_map( { + 'array_number' => 'ArrayNumber' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm index a0b3cdada05..17200d857f3 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm @@ -187,27 +187,18 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, - 'array_of_enum' => { - datatype => 'ARRAY[string]', - base_name => 'array_of_enum', - description => '', - format => '', - read_only => '', - }, }); __PACKAGE__->swagger_types( { 'array_of_string' => 'ARRAY[string]', 'array_array_of_integer' => 'ARRAY[ARRAY[int]]', - 'array_array_of_model' => 'ARRAY[ARRAY[ReadOnlyFirst]]', - 'array_of_enum' => 'ARRAY[string]' + 'array_array_of_model' => 'ARRAY[ARRAY[ReadOnlyFirst]]' } ); __PACKAGE__->attribute_map( { 'array_of_string' => 'array_of_string', 'array_array_of_integer' => 'array_array_of_integer', - 'array_array_of_model' => 'array_array_of_model', - 'array_of_enum' => 'array_of_enum' + 'array_array_of_model' => 'array_array_of_model' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm new file mode 100644 index 00000000000..71072a8c809 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::Client; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'Client', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'client' => { + datatype => 'string', + base_name => 'client', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'client' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'client' => 'client' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm new file mode 100644 index 00000000000..b4afe389e7d --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::EnumArrays; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'EnumArrays', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'just_symbol' => { + datatype => 'string', + base_name => 'just_symbol', + description => '', + format => '', + read_only => '', + }, + 'array_enum' => { + datatype => 'ARRAY[string]', + base_name => 'array_enum', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'just_symbol' => 'string', + 'array_enum' => 'ARRAY[string]' +} ); + +__PACKAGE__->attribute_map( { + 'just_symbol' => 'just_symbol', + 'array_enum' => 'array_enum' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm new file mode 100644 index 00000000000..7cb93df26de --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::HasOnlyReadOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'HasOnlyReadOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'bar' => { + datatype => 'string', + base_name => 'bar', + description => '', + format => '', + read_only => '', + }, + 'foo' => { + datatype => 'string', + base_name => 'foo', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'bar' => 'string', + 'foo' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'bar' => 'bar', + 'foo' => 'foo' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm new file mode 100644 index 00000000000..da748e627dc --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::List; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'List', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + '_123_list' => { + datatype => 'string', + base_name => '123-list', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + '_123_list' => 'string' +} ); + +__PACKAGE__->attribute_map( { + '_123_list' => '123-list' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm new file mode 100644 index 00000000000..5b6f05884b4 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::MapTest; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'MapTest', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'map_map_of_string' => { + datatype => 'HASH[string,HASH[string,string]]', + base_name => 'map_map_of_string', + description => '', + format => '', + read_only => '', + }, + 'map_of_enum_string' => { + datatype => 'HASH[string,string]', + base_name => 'map_of_enum_string', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'map_map_of_string' => 'HASH[string,HASH[string,string]]', + 'map_of_enum_string' => 'HASH[string,string]' +} ); + +__PACKAGE__->attribute_map( { + 'map_map_of_string' => 'map_map_of_string', + 'map_of_enum_string' => 'map_of_enum_string' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm new file mode 100644 index 00000000000..ae3486d8470 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::NumberOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'NumberOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'just_number' => { + datatype => 'Number', + base_name => 'JustNumber', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'just_number' => 'Number' +} ); + +__PACKAGE__->attribute_map( { + 'just_number' => 'JustNumber' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index 4e4fadcbb0e..6c1058b7e59 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -68,7 +68,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2016-06-28T16:35:21.686+08:00', + generated_date => '2016-08-28T15:57:37.016+08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -134,7 +134,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2016-06-28T16:35:21.686+08:00 +=item Build date: 2016-08-28T15:57:37.016+08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen diff --git a/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t b/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t new file mode 100644 index 00000000000..ce67b29d20f --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly'); + +my $instance = WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly'); + diff --git a/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t b/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t new file mode 100644 index 00000000000..bd6d5b2aa32 --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayOfNumberOnly'); + +my $instance = WWW::SwaggerClient::Object::ArrayOfNumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayOfNumberOnly'); + diff --git a/samples/client/petstore/perl/t/ClientTest.t b/samples/client/petstore/perl/t/ClientTest.t new file mode 100644 index 00000000000..210aaf9764b --- /dev/null +++ b/samples/client/petstore/perl/t/ClientTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Client'); + +my $instance = WWW::SwaggerClient::Object::Client->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Client'); + diff --git a/samples/client/petstore/perl/t/EnumArraysTest.t b/samples/client/petstore/perl/t/EnumArraysTest.t new file mode 100644 index 00000000000..5f555e1a2f6 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumArraysTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumArrays'); + +my $instance = WWW::SwaggerClient::Object::EnumArrays->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumArrays'); + diff --git a/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t b/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t new file mode 100644 index 00000000000..e9a5c45fe24 --- /dev/null +++ b/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::HasOnlyReadOnly'); + +my $instance = WWW::SwaggerClient::Object::HasOnlyReadOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::HasOnlyReadOnly'); + diff --git a/samples/client/petstore/perl/t/ListTest.t b/samples/client/petstore/perl/t/ListTest.t new file mode 100644 index 00000000000..b068a9fe2b3 --- /dev/null +++ b/samples/client/petstore/perl/t/ListTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::List'); + +my $instance = WWW::SwaggerClient::Object::List->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::List'); + diff --git a/samples/client/petstore/perl/t/MapTestTest.t b/samples/client/petstore/perl/t/MapTestTest.t new file mode 100644 index 00000000000..29e75ad1f03 --- /dev/null +++ b/samples/client/petstore/perl/t/MapTestTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::MapTest'); + +my $instance = WWW::SwaggerClient::Object::MapTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::MapTest'); + diff --git a/samples/client/petstore/perl/t/NumberOnlyTest.t b/samples/client/petstore/perl/t/NumberOnlyTest.t new file mode 100644 index 00000000000..6c3202a1502 --- /dev/null +++ b/samples/client/petstore/perl/t/NumberOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::NumberOnly'); + +my $instance = WWW::SwaggerClient::Object::NumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::NumberOnly'); + diff --git a/samples/client/petstore/php/.swagger-codegen-ignore b/samples/client/petstore/php/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/php/.swagger-codegen-ignore +++ b/samples/client/petstore/php/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/php/SwaggerClient-php/.php_cs b/samples/client/petstore/php/SwaggerClient-php/.php_cs new file mode 100644 index 00000000000..6b8e23c818a --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/.php_cs @@ -0,0 +1,18 @@ +level(Symfony\CS\FixerInterface::PSR2_LEVEL) + ->setUsingCache(true) + ->fixers( + [ + 'ordered_use', + 'phpdoc_order', + 'short_array_syntax', + 'strict', + 'strict_param' + ] + ) + ->finder( + Symfony\CS\Finder\DefaultFinder::create() + ->in(__DIR__) + ); diff --git a/samples/client/petstore/php/SwaggerClient-php/.travis.yml b/samples/client/petstore/php/SwaggerClient-php/.travis.yml index 3c97d942552..d77f3825f6f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/.travis.yml +++ b/samples/client/petstore/php/SwaggerClient-php/.travis.yml @@ -7,4 +7,4 @@ php: - 7.0 - hhvm before_install: "composer install" -script: "phpunit lib/Tests" +script: "vendor/bin/phpunit" diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 735d53925ae..6089d21da1c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,6 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-06-30T07:09:58.112+02:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -46,7 +45,7 @@ To run the unit tests: ``` composer install -./vendor/bin/phpunit lib/Tests +./vendor/bin/phpunit ``` ## Getting Started @@ -58,12 +57,13 @@ Please follow the [installation procedure](#installation--usage) and then run th require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject__end = "test_code_inject__end_example"; // string | To test code injection =end +$body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model try { - $api_instance->testCodeInjectEnd($test_code_inject__end); + $result = $api_instance->testClientModel($body); + print_r($result); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testCodeInjectEnd: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testClientModel: ', $e->getMessage(), PHP_EOL; } ?> @@ -75,9 +75,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testCodeInjectEnd**](docs/Api/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection =end +*FakeApi* | [**testClientModel**](docs/Api/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumQueryParameters**](docs/Api/FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**testEnumParameters**](docs/Api/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters *PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store *PetApi* | [**deletePet**](docs/Api/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/Api/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -111,7 +111,9 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/Model/ArrayTest.md) - [Cat](docs/Model/Cat.md) - [Category](docs/Model/Category.md) + - [Client](docs/Model/Client.md) - [Dog](docs/Model/Dog.md) + - [EnumArrays](docs/Model/EnumArrays.md) - [EnumClass](docs/Model/EnumClass.md) - [EnumTest](docs/Model/EnumTest.md) - [FormatTest](docs/Model/FormatTest.md) @@ -119,6 +121,7 @@ Class | Method | HTTP request | Description - [MapTest](docs/Model/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model/Model200Response.md) + - [ModelList](docs/Model/ModelList.md) - [ModelReturn](docs/Model/ModelReturn.md) - [Name](docs/Model/Name.md) - [NumberOnly](docs/Model/NumberOnly.md) @@ -133,6 +136,16 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## http_basic_test + +- **Type**: HTTP basic authentication + ## petstore_auth - **Type**: OAuth @@ -142,12 +155,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index b9290bdacb9..78602f3be45 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -8,7 +8,7 @@ "api" ], "homepage": "http://swagger.io", - "license": "Apache v2", + "license": "Apache-2.0", "authors": [ { "name": "Swagger and contributors", @@ -24,7 +24,8 @@ "require-dev": { "phpunit/phpunit": "~4.8", "satooshi/php-coveralls": "~1.0", - "squizlabs/php_codesniffer": "~2.6" + "squizlabs/php_codesniffer": "~2.6", + "friendsofphp/php-cs-fixer": "~1.12" }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } 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 5a8096f547f..249841b68e9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters -# **testCodeInjectEnd** -> testCodeInjectEnd($test_code_inject__end) +# **testClientModel** +> \Swagger\Client\Model\Client testClientModel($body) -To test code injection =end +To test \"client\" model ### Example ```php @@ -20,12 +20,13 @@ To test code injection =end require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject__end = "test_code_inject__end_example"; // string | To test code injection =end +$body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model try { - $api_instance->testCodeInjectEnd($test_code_inject__end); + $result = $api_instance->testClientModel($body); + print_r($result); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testCodeInjectEnd: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testClientModel: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -34,11 +35,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test_code_inject__end** | **string**| To test code injection =end | [optional] + **body** | [**\Swagger\Client\Model\Client**](../Model/\Swagger\Client\Model\Client.md)| client model | ### Return type -void (empty response body) +[**\Swagger\Client\Model\Client**](../Model/Client.md) ### Authorization @@ -46,13 +47,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **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** -> testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) +> testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,22 +64,27 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン setUsername('YOUR_USERNAME'); +Swagger\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); + $api_instance = new Swagger\Client\Api\FakeApi(); $number = 3.4; // float | None $double = 1.2; // double | None -$string = "string_example"; // string | None +$pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None $byte = "B"; // string | None $integer = 56; // int | None $int32 = 56; // int | None $int64 = 789; // int | None $float = 3.4; // float | None +$string = "string_example"; // string | None $binary = "B"; // string | None $date = new \DateTime(); // \DateTime | None $date_time = new \DateTime(); // \DateTime | None $password = "password_example"; // string | None try { - $api_instance->testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + $api_instance->testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password); } catch (Exception $e) { echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; } @@ -91,12 +97,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **float**| None | **double** | **double**| None | - **string** | **string**| None | + **pattern_without_delimiter** | **string**| None | **byte** | **string**| None | **integer** | **int**| None | [optional] **int32** | **int**| None | [optional] **int64** | **int**| None | [optional] **float** | **float**| None | [optional] + **string** | **string**| None | [optional] **binary** | **string**| None | [optional] **date** | **\DateTime**| None | [optional] **date_time** | **\DateTime**| None | [optional] @@ -108,7 +115,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../../README.md#http_basic_test) ### HTTP request headers @@ -117,10 +124,10 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) -# **testEnumQueryParameters** -> testEnumQueryParameters($enum_query_string, $enum_query_integer, $enum_query_double) +# **testEnumParameters** +> 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) -To test enum query parameters +To test enum parameters ### Example ```php @@ -128,14 +135,19 @@ To test enum query parameters require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); +$enum_form_string_array = array("enum_form_string_array_example"); // string[] | Form parameter enum test (string array) +$enum_form_string = "-efg"; // string | Form parameter enum test (string) +$enum_header_string_array = array("enum_header_string_array_example"); // string[] | Header parameter enum test (string array) +$enum_header_string = "-efg"; // string | Header parameter enum test (string) +$enum_query_string_array = array("enum_query_string_array_example"); // string[] | Query parameter enum test (string array) $enum_query_string = "-efg"; // string | Query parameter enum test (string) $enum_query_integer = 3.4; // float | Query parameter enum test (double) $enum_query_double = 1.2; // double | Query parameter enum test (double) try { - $api_instance->testEnumQueryParameters($enum_query_string, $enum_query_integer, $enum_query_double); + $api_instance->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->testEnumQueryParameters: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testEnumParameters: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -144,6 +156,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**string[]**](../Model/string.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**string[]**](../Model/string.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**string[]**](../Model/string.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **float**| Query parameter enum test (double) | [optional] **enum_query_double** | **double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md new file mode 100644 index 00000000000..f6047a62471 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumArrays.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumArrays.md new file mode 100644 index 00000000000..ebaedecdae0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **string** | | [optional] +**array_enum** | **string[]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md new file mode 100644 index 00000000000..e18ba4e123d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md @@ -0,0 +1,10 @@ +# ModelList + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 4c1c1c04ed2..a88a92b4b93 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -40,9 +40,9 @@ namespace Swagger\Client\Api; -use \Swagger\Client\Configuration; use \Swagger\Client\ApiClient; use \Swagger\Client\ApiException; +use \Swagger\Client\Configuration; use \Swagger\Client\ObjectSerializer; /** @@ -51,12 +51,11 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FakeApi { - /** * API Client * @@ -71,7 +70,7 @@ class FakeApi */ public function __construct(\Swagger\Client\ApiClient $apiClient = null) { - if ($apiClient == null) { + if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } @@ -103,51 +102,56 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) } /** - * Operation testCodeInjectEnd + * Operation testClientModel * - * To test code injection =end + * To test \"client\" model * - * @param string $test_code_inject__end To test code injection =end (optional) - * @return void + * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Client */ - public function testCodeInjectEnd($test_code_inject__end = null) + public function testClientModel($body) { - list($response) = $this->testCodeInjectEndWithHttpInfo($test_code_inject__end); + list($response) = $this->testClientModelWithHttpInfo($body); return $response; } /** - * Operation testCodeInjectEndWithHttpInfo + * Operation testClientModelWithHttpInfo * - * To test code injection =end + * To test \"client\" model * - * @param string $test_code_inject__end To test code injection =end (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ - public function testCodeInjectEndWithHttpInfo($test_code_inject__end = null) + public function testClientModelWithHttpInfo($body) { + // verify the required parameter 'body' is set + if ($body === null) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); + } // parse inputs $resourcePath = "/fake"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*/ end')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*/ =end));(phpinfo(')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); - // form params - if ($test_code_inject__end !== null) { - $formParams['test code inject */ =end'] = $this->apiClient->getSerializer()->toFormValue($test_code_inject__end); + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -158,17 +162,21 @@ public function testCodeInjectEndWithHttpInfo($test_code_inject__end = null) try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, - 'PUT', + 'PATCH', $queryParams, $httpBody, $headerParams, - null, + '\Swagger\Client\Model\Client', '/fake' ); - return array(null, $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Client', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Client', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -182,22 +190,23 @@ public function testCodeInjectEndWithHttpInfo($test_code_inject__end = null) * * @param float $number None (required) * @param double $double None (required) - * @param string $string None (required) + * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) * @param int $int32 None (optional) * @param int $int64 None (optional) * @param float $float None (optional) + * @param string $string None (optional) * @param string $binary None (optional) * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ - public function testEndpointParameters($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) + public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null) { - list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password); return $response; } @@ -208,29 +217,30 @@ public function testEndpointParameters($number, $double, $string, $byte, $intege * * @param float $number None (required) * @param double $double None (required) - * @param string $string None (required) + * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) * @param int $int32 None (optional) * @param int $int64 None (optional) * @param float $float None (optional) + * @param string $string None (optional) * @param string $binary None (optional) * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ - public function testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) + public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null) { // verify the required parameter 'number' is set if ($number === null) { throw new \InvalidArgumentException('Missing the required parameter $number when calling testEndpointParameters'); } - if ($number > 543.2) { + if (($number > 543.2)) { throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 543.2.'); } - if ($number < 32.1) { + if (($number < 32.1)) { throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 32.1.'); } @@ -238,61 +248,65 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b if ($double === null) { throw new \InvalidArgumentException('Missing the required parameter $double when calling testEndpointParameters'); } - if ($double > 123.4) { + if (($double > 123.4)) { throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 123.4.'); } - if ($double < 67.8) { + if (($double < 67.8)) { throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 67.8.'); } - // verify the required parameter 'string' is set - if ($string === null) { - throw new \InvalidArgumentException('Missing the required parameter $string when calling testEndpointParameters'); + // verify the required parameter 'pattern_without_delimiter' is set + if ($pattern_without_delimiter === null) { + throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } - if (!preg_match("/[a-z]/i", $string)) { - throw new \InvalidArgumentException('invalid value for "string" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter)) { + throw new \InvalidArgumentException("invalid value for \"pattern_without_delimiter\" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*_/."); } // verify the required parameter 'byte' is set if ($byte === null) { throw new \InvalidArgumentException('Missing the required parameter $byte when calling testEndpointParameters'); } - if ($integer > 100.0) { + if (!is_null($integer) && ($integer > 100.0)) { throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.0.'); } - if ($integer < 10.0) { + if (!is_null($integer) && ($integer < 10.0)) { throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.0.'); } - if ($int32 > 200.0) { + if (!is_null($int32) && ($int32 > 200.0)) { throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.0.'); } - if ($int32 < 20.0) { + if (!is_null($int32) && ($int32 < 20.0)) { throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.0.'); } - if ($float > 987.6) { + if (!is_null($float) && ($float > 987.6)) { throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); } - if (strlen($password) > 64) { + if (!is_null($string) && !preg_match("/[a-z]/i", $string)) { + throw new \InvalidArgumentException("invalid value for \"string\" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i."); + } + + if (!is_null($password) && (strlen($password) > 64)) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); } - if (strlen($password) < 10) { + if (!is_null($password) && (strlen($password) < 10)) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } // parse inputs $resourcePath = "/fake"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml; charset=utf-8', 'application/json; charset=utf-8')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/xml; charset=utf-8','application/json; charset=utf-8')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/xml; charset=utf-8', 'application/json; charset=utf-8']); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -326,6 +340,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b $formParams['string'] = $this->apiClient->getSerializer()->toFormValue($string); } // form params + if ($pattern_without_delimiter !== null) { + $formParams['pattern_without_delimiter'] = $this->apiClient->getSerializer()->toFormValue($pattern_without_delimiter); + } + // form params if ($byte !== null) { $formParams['byte'] = $this->apiClient->getSerializer()->toFormValue($byte); } @@ -352,6 +370,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } + // this endpoint requires HTTP basic authentication + if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { + $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); + } // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -364,7 +386,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b '/fake' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -374,57 +396,93 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b } /** - * Operation testEnumQueryParameters + * Operation testEnumParameters * - * To test enum query parameters + * To test enum parameters * + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) * @param float $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ - public function testEnumQueryParameters($enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) + public function testEnumParameters($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { - list($response) = $this->testEnumQueryParametersWithHttpInfo($enum_query_string, $enum_query_integer, $enum_query_double); + list($response) = $this->testEnumParametersWithHttpInfo($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 $response; } /** - * Operation testEnumQueryParametersWithHttpInfo + * Operation testEnumParametersWithHttpInfo * - * To test enum query parameters + * To test enum parameters * + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) * @param float $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ - public function testEnumQueryParametersWithHttpInfo($enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) + public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { // parse inputs $resourcePath = "/fake"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); + // query params + if (is_array($enum_query_string_array)) { + $enum_query_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_query_string_array, 'csv', true); + } + if ($enum_query_string_array !== null) { + $queryParams['enum_query_string_array'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_string_array); + } + // query params + if ($enum_query_string !== null) { + $queryParams['enum_query_string'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_string); + } // query params if ($enum_query_integer !== null) { $queryParams['enum_query_integer'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_integer); } + // header params + if (is_array($enum_header_string_array)) { + $enum_header_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_header_string_array, 'csv'); + } + if ($enum_header_string_array !== null) { + $headerParams['enum_header_string_array'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string_array); + } + // header params + if ($enum_header_string !== null) { + $headerParams['enum_header_string'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string); + } // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); // form params - if ($enum_query_string !== null) { - $formParams['enum_query_string'] = $this->apiClient->getSerializer()->toFormValue($enum_query_string); + if ($enum_form_string_array !== null) { + $formParams['enum_form_string_array'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string_array); + } + // form params + if ($enum_form_string !== null) { + $formParams['enum_form_string'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string); } // form params if ($enum_query_double !== null) { @@ -449,7 +507,7 @@ public function testEnumQueryParametersWithHttpInfo($enum_query_string = null, $ '/fake' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -457,5 +515,4 @@ public function testEnumQueryParametersWithHttpInfo($enum_query_string = null, $ throw $e; } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 98ebca4f6dd..791e3c99047 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -40,9 +40,9 @@ namespace Swagger\Client\Api; -use \Swagger\Client\Configuration; use \Swagger\Client\ApiClient; use \Swagger\Client\ApiException; +use \Swagger\Client\Configuration; use \Swagger\Client\ObjectSerializer; /** @@ -51,12 +51,11 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class PetApi { - /** * API Client * @@ -71,7 +70,7 @@ class PetApi */ public function __construct(\Swagger\Client\ApiClient $apiClient = null) { - if ($apiClient == null) { + if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } @@ -108,8 +107,8 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) * Add a new pet to the store * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function addPet($body) { @@ -123,8 +122,8 @@ public function addPet($body) * Add a new pet to the store * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function addPetWithHttpInfo($body) { @@ -135,14 +134,14 @@ public function addPetWithHttpInfo($body) // parse inputs $resourcePath = "/pet"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', 'application/xml']); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -175,7 +174,7 @@ public function addPetWithHttpInfo($body) '/pet' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -191,8 +190,8 @@ public function addPetWithHttpInfo($body) * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function deletePet($pet_id, $api_key = null) { @@ -207,8 +206,8 @@ public function deletePet($pet_id, $api_key = null) * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deletePetWithHttpInfo($pet_id, $api_key = null) { @@ -219,14 +218,14 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // header params if ($api_key !== null) { @@ -266,7 +265,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) '/pet/{petId}' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -281,8 +280,8 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) * Finds Pets by status * * @param string[] $status Status values that need to be considered for filter (required) - * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Pet[] */ public function findPetsByStatus($status) { @@ -296,8 +295,8 @@ public function findPetsByStatus($status) * Finds Pets by status * * @param string[] $status Status values that need to be considered for filter (required) - * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByStatusWithHttpInfo($status) { @@ -308,14 +307,14 @@ public function findPetsByStatusWithHttpInfo($status) // parse inputs $resourcePath = "/pet/findByStatus"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // query params if (is_array($status)) { @@ -350,7 +349,7 @@ public function findPetsByStatusWithHttpInfo($status) '/pet/findByStatus' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -369,8 +368,8 @@ public function findPetsByStatusWithHttpInfo($status) * Finds Pets by tags * * @param string[] $tags Tags to filter by (required) - * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Pet[] */ public function findPetsByTags($tags) { @@ -384,8 +383,8 @@ public function findPetsByTags($tags) * Finds Pets by tags * * @param string[] $tags Tags to filter by (required) - * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByTagsWithHttpInfo($tags) { @@ -396,14 +395,14 @@ public function findPetsByTagsWithHttpInfo($tags) // parse inputs $resourcePath = "/pet/findByTags"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // query params if (is_array($tags)) { @@ -438,7 +437,7 @@ public function findPetsByTagsWithHttpInfo($tags) '/pet/findByTags' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -457,8 +456,8 @@ public function findPetsByTagsWithHttpInfo($tags) * Find pet by ID * * @param int $pet_id ID of pet to return (required) - * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Pet */ public function getPetById($pet_id) { @@ -472,8 +471,8 @@ public function getPetById($pet_id) * Find pet by ID * * @param int $pet_id ID of pet to return (required) - * @return Array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ public function getPetByIdWithHttpInfo($pet_id) { @@ -484,14 +483,14 @@ public function getPetByIdWithHttpInfo($pet_id) // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // path params if ($pet_id !== null) { @@ -528,7 +527,7 @@ public function getPetByIdWithHttpInfo($pet_id) '/pet/{petId}' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -547,8 +546,8 @@ public function getPetByIdWithHttpInfo($pet_id) * Update an existing pet * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function updatePet($body) { @@ -562,8 +561,8 @@ public function updatePet($body) * Update an existing pet * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithHttpInfo($body) { @@ -574,14 +573,14 @@ public function updatePetWithHttpInfo($body) // parse inputs $resourcePath = "/pet"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', 'application/xml']); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -614,7 +613,7 @@ public function updatePetWithHttpInfo($body) '/pet' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -631,8 +630,8 @@ public function updatePetWithHttpInfo($body) * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function updatePetWithForm($pet_id, $name = null, $status = null) { @@ -648,8 +647,8 @@ public function updatePetWithForm($pet_id, $name = null, $status = null) * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) { @@ -660,14 +659,14 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/x-www-form-urlencoded']); // path params if ($pet_id !== null) { @@ -711,7 +710,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n '/pet/{petId}' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -728,8 +727,8 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) - * @return \Swagger\Client\Model\ApiResponse * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\ApiResponse */ public function uploadFile($pet_id, $additional_metadata = null, $file = null) { @@ -745,8 +744,8 @@ public function uploadFile($pet_id, $additional_metadata = null, $file = null) * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) - * @return Array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) { @@ -757,14 +756,14 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['multipart/form-data']); // path params if ($pet_id !== null) { @@ -814,7 +813,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi '/pet/{petId}/uploadImage' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -826,5 +825,4 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi throw $e; } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 6f8bf19eb24..7d34e608139 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -40,9 +40,9 @@ namespace Swagger\Client\Api; -use \Swagger\Client\Configuration; use \Swagger\Client\ApiClient; use \Swagger\Client\ApiException; +use \Swagger\Client\Configuration; use \Swagger\Client\ObjectSerializer; /** @@ -51,12 +51,11 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class StoreApi { - /** * API Client * @@ -71,7 +70,7 @@ class StoreApi */ public function __construct(\Swagger\Client\ApiClient $apiClient = null) { - if ($apiClient == null) { + if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } @@ -108,8 +107,8 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function deleteOrder($order_id) { @@ -123,8 +122,8 @@ public function deleteOrder($order_id) * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteOrderWithHttpInfo($order_id) { @@ -132,21 +131,21 @@ public function deleteOrderWithHttpInfo($order_id) if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } - if ($order_id < 1.0) { + if (($order_id < 1.0)) { throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); } // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // path params if ($order_id !== null) { @@ -178,7 +177,7 @@ public function deleteOrderWithHttpInfo($order_id) '/store/order/{orderId}' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -192,8 +191,8 @@ public function deleteOrderWithHttpInfo($order_id) * * Returns pet inventories by status * - * @return map[string,int] * @throws \Swagger\Client\ApiException on non-2xx response + * @return map[string,int] */ public function getInventory() { @@ -206,22 +205,22 @@ public function getInventory() * * Returns pet inventories by status * - * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings) */ public function getInventoryWithHttpInfo() { // parse inputs $resourcePath = "/store/inventory"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -250,7 +249,7 @@ public function getInventoryWithHttpInfo() '/store/inventory' ); - return array($this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -269,8 +268,8 @@ public function getInventoryWithHttpInfo() * Find purchase order by ID * * @param int $order_id ID of pet that needs to be fetched (required) - * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Order */ public function getOrderById($order_id) { @@ -284,8 +283,8 @@ public function getOrderById($order_id) * Find purchase order by ID * * @param int $order_id ID of pet that needs to be fetched (required) - * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function getOrderByIdWithHttpInfo($order_id) { @@ -293,24 +292,24 @@ public function getOrderByIdWithHttpInfo($order_id) if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } - if ($order_id > 5.0) { + if (($order_id > 5.0)) { throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.0.'); } - if ($order_id < 1.0) { + if (($order_id < 1.0)) { throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); } // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // path params if ($order_id !== null) { @@ -342,7 +341,7 @@ public function getOrderByIdWithHttpInfo($order_id) '/store/order/{orderId}' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -361,8 +360,8 @@ public function getOrderByIdWithHttpInfo($order_id) * Place an order for a pet * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) - * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Order */ public function placeOrder($body) { @@ -376,8 +375,8 @@ public function placeOrder($body) * Place an order for a pet * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) - * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function placeOrderWithHttpInfo($body) { @@ -388,14 +387,14 @@ public function placeOrderWithHttpInfo($body) // parse inputs $resourcePath = "/store/order"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -424,7 +423,7 @@ public function placeOrderWithHttpInfo($body) '/store/order' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -436,5 +435,4 @@ public function placeOrderWithHttpInfo($body) throw $e; } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ac046ad5086..f4319be34b3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -40,9 +40,9 @@ namespace Swagger\Client\Api; -use \Swagger\Client\Configuration; use \Swagger\Client\ApiClient; use \Swagger\Client\ApiException; +use \Swagger\Client\Configuration; use \Swagger\Client\ObjectSerializer; /** @@ -51,12 +51,11 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class UserApi { - /** * API Client * @@ -71,7 +70,7 @@ class UserApi */ public function __construct(\Swagger\Client\ApiClient $apiClient = null) { - if ($apiClient == null) { + if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } @@ -108,8 +107,8 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) * Create user * * @param \Swagger\Client\Model\User $body Created user object (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function createUser($body) { @@ -123,8 +122,8 @@ public function createUser($body) * Create user * * @param \Swagger\Client\Model\User $body Created user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUserWithHttpInfo($body) { @@ -135,14 +134,14 @@ public function createUserWithHttpInfo($body) // parse inputs $resourcePath = "/user"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -171,7 +170,7 @@ public function createUserWithHttpInfo($body) '/user' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -186,8 +185,8 @@ public function createUserWithHttpInfo($body) * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function createUsersWithArrayInput($body) { @@ -201,8 +200,8 @@ public function createUsersWithArrayInput($body) * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUsersWithArrayInputWithHttpInfo($body) { @@ -213,14 +212,14 @@ public function createUsersWithArrayInputWithHttpInfo($body) // parse inputs $resourcePath = "/user/createWithArray"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -249,7 +248,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) '/user/createWithArray' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -264,8 +263,8 @@ public function createUsersWithArrayInputWithHttpInfo($body) * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function createUsersWithListInput($body) { @@ -279,8 +278,8 @@ public function createUsersWithListInput($body) * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUsersWithListInputWithHttpInfo($body) { @@ -291,14 +290,14 @@ public function createUsersWithListInputWithHttpInfo($body) // parse inputs $resourcePath = "/user/createWithList"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -327,7 +326,7 @@ public function createUsersWithListInputWithHttpInfo($body) '/user/createWithList' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -342,8 +341,8 @@ public function createUsersWithListInputWithHttpInfo($body) * Delete user * * @param string $username The name that needs to be deleted (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function deleteUser($username) { @@ -357,8 +356,8 @@ public function deleteUser($username) * Delete user * * @param string $username The name that needs to be deleted (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteUserWithHttpInfo($username) { @@ -369,14 +368,14 @@ public function deleteUserWithHttpInfo($username) // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // path params if ($username !== null) { @@ -408,7 +407,7 @@ public function deleteUserWithHttpInfo($username) '/user/{username}' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -423,8 +422,8 @@ public function deleteUserWithHttpInfo($username) * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\User */ public function getUserByName($username) { @@ -438,8 +437,8 @@ public function getUserByName($username) * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @return Array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) */ public function getUserByNameWithHttpInfo($username) { @@ -450,14 +449,14 @@ public function getUserByNameWithHttpInfo($username) // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // path params if ($username !== null) { @@ -489,7 +488,7 @@ public function getUserByNameWithHttpInfo($username) '/user/{username}' ); - return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -509,8 +508,8 @@ public function getUserByNameWithHttpInfo($username) * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) - * @return string * @throws \Swagger\Client\ApiException on non-2xx response + * @return string */ public function loginUser($username, $password) { @@ -525,8 +524,8 @@ public function loginUser($username, $password) * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) - * @return Array of string, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of string, HTTP status code, HTTP response headers (array of strings) */ public function loginUserWithHttpInfo($username, $password) { @@ -541,14 +540,14 @@ public function loginUserWithHttpInfo($username, $password) // parse inputs $resourcePath = "/user/login"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // query params if ($username !== null) { @@ -580,7 +579,7 @@ public function loginUserWithHttpInfo($username, $password) '/user/login' ); - return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); + return [$this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -598,8 +597,8 @@ public function loginUserWithHttpInfo($username, $password) * * Logs out current logged in user session * - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function logoutUser() { @@ -612,22 +611,22 @@ public function logoutUser() * * Logs out current logged in user session * - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function logoutUserWithHttpInfo() { // parse inputs $resourcePath = "/user/logout"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -651,7 +650,7 @@ public function logoutUserWithHttpInfo() '/user/logout' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -667,8 +666,8 @@ public function logoutUserWithHttpInfo() * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function updateUser($username, $body) { @@ -683,8 +682,8 @@ public function updateUser($username, $body) * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updateUserWithHttpInfo($username, $body) { @@ -699,14 +698,14 @@ public function updateUserWithHttpInfo($username, $body) // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/xml', 'application/json')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); // path params if ($username !== null) { @@ -743,7 +742,7 @@ public function updateUserWithHttpInfo($username, $body) '/user/{username}' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -751,5 +750,4 @@ public function updateUserWithHttpInfo($username, $body) throw $e; } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 45feec1a287..309bbc84760 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,12 +47,11 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClient { - public static $PATCH = "PATCH"; public static $POST = "POST"; public static $GET = "GET"; @@ -82,7 +81,7 @@ class ApiClient */ public function __construct(\Swagger\Client\Configuration $config = null) { - if ($config == null) { + if ($config === null) { $config = Configuration::getDefaultConfiguration(); } @@ -151,8 +150,7 @@ public function getApiKeyWithPrefix($apiKeyIdentifier) */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) { - - $headers = array(); + $headers = []; // construct the http header $headerParams = array_merge( @@ -165,9 +163,9 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header } // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model $postData = json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($postData)); } @@ -175,7 +173,7 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header $curl = curl_init(); // set timeout, if needed - if ($this->config->getCurlTimeout() != 0) { + if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just true @@ -184,7 +182,7 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // disable SSL verification, if needed - if ($this->config->getSSLVerification() == false) { + if ($this->config->getSSLVerification() === false) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } @@ -193,24 +191,24 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header $url = ($url . '?' . http_build_query($queryParams)); } - if ($method == self::$POST) { + if ($method === self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$HEAD) { + } elseif ($method === self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method == self::$OPTIONS) { + } elseif ($method === self::$OPTIONS) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$PATCH) { + } elseif ($method === self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$PUT) { + } elseif ($method === self::$PUT) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$DELETE) { + } elseif ($method === self::$DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method != self::$GET) { + } elseif ($method !== self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -244,12 +242,24 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header } // Handle the response - if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + if ($response_info['http_code'] === 0) { + $curl_error_message = curl_error($curl); + + // curl_exec can sometimes fail but still return a blank message from curl_error(). + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; + } else { + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; + } + + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); + throw $exception; } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file - if ($responseType == '\SplFileObject' || $responseType == 'string') { - return array($http_body, $response_info['http_code'], $http_header); + if ($responseType === '\SplFileObject' || $responseType === 'string') { + return [$http_body, $response_info['http_code'], $http_header]; } $data = json_decode($http_body); @@ -269,7 +279,7 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header $data ); } - return array($data, $response_info['http_code'], $http_header); + return [$data, $response_info['http_code'], $http_header]; } /** @@ -318,7 +328,7 @@ public function selectHeaderContentType($content_type) protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = array(); + $headers = []; $key = ''; foreach (explode("\n", $raw_headers) as $h) { @@ -328,14 +338,14 @@ protected function httpParseHeaders($raw_headers) if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); + $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); } else { - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); + $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); } $key = $h[0]; } else { - if (substr($h[0], 0, 1) == "\t") { + if (substr($h[0], 0, 1) === "\t") { $headers[$key] .= "\r\n\t".trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 48551429c7f..de692b68b96 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiException extends Exception diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 98bb4ab2c17..f08db712f37 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,12 +47,11 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Configuration { - private static $defaultConfiguration = null; /** @@ -60,14 +59,14 @@ class Configuration * * @var string[] */ - protected $apiKeys = array(); + protected $apiKeys = []; /** * Associate array to store API prefix (e.g. Bearer) * * @var string[] */ - protected $apiKeyPrefixes = array(); + protected $apiKeyPrefixes = []; /** * Access token for OAuth @@ -91,11 +90,11 @@ class Configuration protected $password = ''; /** - * The default instance of ApiClient + * The default header(s) * - * @var \Swagger\Client\ApiClient + * @var array */ - protected $defaultHeaders = array(); + protected $defaultHeaders = []; /** * The host @@ -283,7 +282,7 @@ public function getPassword() * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * - * @return ApiClient + * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) { @@ -345,7 +344,7 @@ public function getHost() * * @param string $userAgent the user agent of the api client * - * @return ApiClient + * @return Configuration */ public function setUserAgent($userAgent) { @@ -372,7 +371,7 @@ public function getUserAgent() * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * - * @return ApiClient + * @return Configuration */ public function setCurlTimeout($seconds) { @@ -493,7 +492,7 @@ public function getSSLVerification() */ public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { + if (self::$defaultConfiguration === null) { self::$defaultConfiguration = new Configuration(); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php index 1f64ea68602..604112c2ba4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * AdditionalPropertiesClass Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AdditionalPropertiesClass implements ArrayAccess @@ -65,10 +65,10 @@ class AdditionalPropertiesClass implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'map_property' => 'map[string,string]', 'map_of_map_property' => 'map[string,map[string,string]]' - ); + ]; public static function swaggerTypes() { @@ -79,38 +79,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'map_property' => 'map_property', 'map_of_map_property' => 'map_of_map_property' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'map_property' => 'setMapProperty', 'map_of_map_property' => 'setMapOfMapProperty' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'map_property' => 'getMapProperty', 'map_of_map_property' => 'getMapOfMapProperty' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -125,11 +127,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -144,7 +146,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -259,5 +261,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index d25c852fa6b..4f4bd9126ba 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Animal Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Animal implements ArrayAccess @@ -65,10 +65,10 @@ class Animal implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'class_name' => 'string', 'color' => 'string' - ); + ]; public static function swaggerTypes() { @@ -79,38 +79,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'class_name' => 'className', 'color' => 'color' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'class_name' => 'setClassName', 'color' => 'setColor' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'class_name' => 'getClassName', 'color' => 'getColor' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -125,11 +127,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -148,7 +150,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; if ($this->container['class_name'] === null) { $invalid_properties[] = "'class_name' can't be null"; } @@ -269,5 +271,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index e5c3849fac7..cf65a9cdc1a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * AnimalFarm Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AnimalFarm implements ArrayAccess @@ -65,9 +65,9 @@ class AnimalFarm implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -138,7 +140,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -211,5 +213,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 767a4340343..edd3dcee547 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * ApiResponse Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiResponse implements ArrayAccess @@ -65,11 +65,11 @@ class ApiResponse implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'code' => 'int', 'type' => 'string', 'message' => 'string' - ); + ]; public static function swaggerTypes() { @@ -80,41 +80,43 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'code' => 'code', 'type' => 'type', 'message' => 'message' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'code' => 'setCode', 'type' => 'setType', 'message' => 'setMessage' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'code' => 'getCode', 'type' => 'getType', 'message' => 'getMessage' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -129,11 +131,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -149,7 +151,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -285,5 +287,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index 6f7133db758..ecb06038a08 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * ArrayOfArrayOfNumberOnly Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfArrayOfNumberOnly implements ArrayAccess @@ -65,9 +65,9 @@ class ArrayOfArrayOfNumberOnly implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'array_array_number' => 'float[][]' - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'array_array_number' => 'ArrayArrayNumber' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'array_array_number' => 'setArrayArrayNumber' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'array_array_number' => 'getArrayArrayNumber' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -139,7 +141,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -233,5 +235,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php index 1548460932b..961af5b039f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * ArrayOfNumberOnly Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfNumberOnly implements ArrayAccess @@ -65,9 +65,9 @@ class ArrayOfNumberOnly implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'array_number' => 'float[]' - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'array_number' => 'ArrayNumber' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'array_number' => 'setArrayNumber' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'array_number' => 'getArrayNumber' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -139,7 +141,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -233,5 +235,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php index 5e8f450368a..790cf9fdaf5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * ArrayTest Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayTest implements ArrayAccess @@ -65,11 +65,11 @@ class ArrayTest implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'array_of_string' => 'string[]', 'array_array_of_integer' => 'int[][]', 'array_array_of_model' => '\Swagger\Client\Model\ReadOnlyFirst[][]' - ); + ]; public static function swaggerTypes() { @@ -80,41 +80,43 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'array_of_string' => 'array_of_string', 'array_array_of_integer' => 'array_array_of_integer', 'array_array_of_model' => 'array_array_of_model' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'array_of_string' => 'setArrayOfString', 'array_array_of_integer' => 'setArrayArrayOfInteger', 'array_array_of_model' => 'setArrayArrayOfModel' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'array_of_string' => 'getArrayOfString', 'array_array_of_integer' => 'getArrayArrayOfInteger', 'array_array_of_model' => 'getArrayArrayOfModel' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -129,11 +131,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -149,7 +151,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -285,5 +287,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 0245b27774b..a7ff369dd9c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Cat Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Cat extends Animal implements ArrayAccess @@ -65,9 +65,9 @@ class Cat extends Animal implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'declawed' => 'bool' - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'declawed' => 'declawed' - ); + ]; - public static function attributeMap() - { - return parent::attributeMap() + self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'declawed' => 'setDeclawed' - ); + ]; - public static function setters() - { - return parent::setters() + self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'declawed' => 'getDeclawed' - ); + ]; + + public static function attributeMap() + { + return parent::attributeMap() + self::$attributeMap; + } + + public static function setters() + { + return parent::setters() + self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -141,7 +143,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -235,5 +237,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index a453d750b12..7a1f6d1da1b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Category Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Category implements ArrayAccess @@ -65,10 +65,10 @@ class Category implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'id' => 'int', 'name' => 'string' - ); + ]; public static function swaggerTypes() { @@ -79,38 +79,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'id' => 'id', 'name' => 'name' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'id' => 'setId', 'name' => 'setName' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'id' => 'getId', 'name' => 'getName' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -125,11 +127,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -144,7 +146,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -259,5 +261,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php new file mode 100644 index 00000000000..9cb921373be --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -0,0 +1,237 @@ + 'string' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'client' => 'client' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'client' => 'setClient' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'client' => 'getClient' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['client'] = isset($data['client']) ? $data['client'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets client + * @return string + */ + public function getClient() + { + return $this->container['client']; + } + + /** + * Sets client + * @param string $client + * @return $this + */ + public function setClient($client) + { + $this->container['client'] = $client; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index 23530dab46d..387a4ddb076 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Dog Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Dog extends Animal implements ArrayAccess @@ -65,9 +65,9 @@ class Dog extends Animal implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'breed' => 'string' - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'breed' => 'breed' - ); + ]; - public static function attributeMap() - { - return parent::attributeMap() + self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'breed' => 'setBreed' - ); + ]; - public static function setters() - { - return parent::setters() + self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'breed' => 'getBreed' - ); + ]; + + public static function attributeMap() + { + return parent::attributeMap() + self::$attributeMap; + } + + public static function setters() + { + return parent::setters() + self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -141,7 +143,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -235,5 +237,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php new file mode 100644 index 00000000000..4287780f2a5 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -0,0 +1,308 @@ + 'string', + 'array_enum' => 'string[]' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'just_symbol' => 'just_symbol', + 'array_enum' => 'array_enum' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'just_symbol' => 'setJustSymbol', + 'array_enum' => 'setArrayEnum' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'just_symbol' => 'getJustSymbol', + 'array_enum' => 'getArrayEnum' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + const JUST_SYMBOL_ = '>='; + const JUST_SYMBOL_ = '$'; + const ARRAY_ENUM_FISH = 'fish'; + const ARRAY_ENUM_CRAB = 'crab'; + + + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getJustSymbolAllowableValues() + { + return [ + self::JUST_SYMBOL_, + self::JUST_SYMBOL_, + ]; + } + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getArrayEnumAllowableValues() + { + return [ + self::ARRAY_ENUM_FISH, + self::ARRAY_ENUM_CRAB, + ]; + } + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['just_symbol'] = isset($data['just_symbol']) ? $data['just_symbol'] : null; + $this->container['array_enum'] = isset($data['array_enum']) ? $data['array_enum'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + $allowed_values = [">=", "$"]; + if (!in_array($this->container['just_symbol'], $allowed_values)) { + $invalid_properties[] = "invalid value for 'just_symbol', must be one of #{allowed_values}."; + } + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + $allowed_values = [">=", "$"]; + if (!in_array($this->container['just_symbol'], $allowed_values)) { + return false; + } + return true; + } + + + /** + * Gets just_symbol + * @return string + */ + public function getJustSymbol() + { + return $this->container['just_symbol']; + } + + /** + * Sets just_symbol + * @param string $just_symbol + * @return $this + */ + public function setJustSymbol($just_symbol) + { + $allowed_values = array('>=', '$'); + if (!is_null($just_symbol) && (!in_array($just_symbol, $allowed_values))) { + throw new \InvalidArgumentException("Invalid value for 'just_symbol', must be one of '>=', '$'"); + } + $this->container['just_symbol'] = $just_symbol; + + return $this; + } + + /** + * Gets array_enum + * @return string[] + */ + public function getArrayEnum() + { + return $this->container['array_enum']; + } + + /** + * Sets array_enum + * @param string[] $array_enum + * @return $this + */ + public function setArrayEnum($array_enum) + { + $allowed_values = array('fish', 'crab'); + if (!is_null($array_enum) && (array_diff($array_enum, $allowed_values))) { + throw new \InvalidArgumentException("Invalid value for 'array_enum', must be one of 'fish', 'crab'"); + } + $this->container['array_enum'] = $array_enum; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index 61014fa3959..33c8405a7eb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * EnumClass Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumClass { @@ -61,5 +61,3 @@ class EnumClass { } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 49fc40c8574..dbc63779de5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * EnumTest Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumTest implements ArrayAccess @@ -65,11 +65,11 @@ class EnumTest implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'enum_string' => 'string', 'enum_integer' => 'int', 'enum_number' => 'double' - ); + ]; public static function swaggerTypes() { @@ -80,41 +80,43 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'enum_string' => 'enum_string', 'enum_integer' => 'enum_integer', 'enum_number' => 'enum_number' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'enum_string' => 'setEnumString', 'enum_integer' => 'setEnumInteger', 'enum_number' => 'setEnumNumber' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'enum_string' => 'getEnumString', 'enum_integer' => 'getEnumInteger', 'enum_number' => 'getEnumNumber' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -171,11 +173,11 @@ public function getEnumNumberAllowableValues() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -191,19 +193,22 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); - $allowed_values = array("UPPER", "lower"); + $invalid_properties = []; + $allowed_values = ["UPPER", "lower"]; if (!in_array($this->container['enum_string'], $allowed_values)) { $invalid_properties[] = "invalid value for 'enum_string', must be one of #{allowed_values}."; } - $allowed_values = array("1", "-1"); + + $allowed_values = ["1", "-1"]; if (!in_array($this->container['enum_integer'], $allowed_values)) { $invalid_properties[] = "invalid value for 'enum_integer', must be one of #{allowed_values}."; } - $allowed_values = array("1.1", "-1.2"); + + $allowed_values = ["1.1", "-1.2"]; if (!in_array($this->container['enum_number'], $allowed_values)) { $invalid_properties[] = "invalid value for 'enum_number', must be one of #{allowed_values}."; } + return $invalid_properties; } @@ -215,15 +220,15 @@ public function listInvalidProperties() */ public function valid() { - $allowed_values = array("UPPER", "lower"); + $allowed_values = ["UPPER", "lower"]; if (!in_array($this->container['enum_string'], $allowed_values)) { return false; } - $allowed_values = array("1", "-1"); + $allowed_values = ["1", "-1"]; if (!in_array($this->container['enum_integer'], $allowed_values)) { return false; } - $allowed_values = array("1.1", "-1.2"); + $allowed_values = ["1.1", "-1.2"]; if (!in_array($this->container['enum_number'], $allowed_values)) { return false; } @@ -248,7 +253,7 @@ public function getEnumString() public function setEnumString($enum_string) { $allowed_values = array('UPPER', 'lower'); - if (!in_array($enum_string, $allowed_values)) { + if (!is_null($enum_string) && (!in_array($enum_string, $allowed_values))) { throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower'"); } $this->container['enum_string'] = $enum_string; @@ -273,7 +278,7 @@ public function getEnumInteger() public function setEnumInteger($enum_integer) { $allowed_values = array('1', '-1'); - if (!in_array($enum_integer, $allowed_values)) { + if (!is_null($enum_integer) && (!in_array($enum_integer, $allowed_values))) { throw new \InvalidArgumentException("Invalid value for 'enum_integer', must be one of '1', '-1'"); } $this->container['enum_integer'] = $enum_integer; @@ -298,7 +303,7 @@ public function getEnumNumber() public function setEnumNumber($enum_number) { $allowed_values = array('1.1', '-1.2'); - if (!in_array($enum_number, $allowed_values)) { + if (!is_null($enum_number) && (!in_array($enum_number, $allowed_values))) { throw new \InvalidArgumentException("Invalid value for 'enum_number', must be one of '1.1', '-1.2'"); } $this->container['enum_number'] = $enum_number; @@ -363,5 +368,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index b2bbb6806a1..76a944104f2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * FormatTest Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FormatTest implements ArrayAccess @@ -65,7 +65,7 @@ class FormatTest implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'integer' => 'int', 'int32' => 'int', 'int64' => 'int', @@ -79,7 +79,7 @@ class FormatTest implements ArrayAccess 'date_time' => '\DateTime', 'uuid' => 'string', 'password' => 'string' - ); + ]; public static function swaggerTypes() { @@ -90,7 +90,7 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'integer' => 'integer', 'int32' => 'int32', 'int64' => 'int64', @@ -104,18 +104,14 @@ public static function swaggerTypes() 'date_time' => 'dateTime', 'uuid' => 'uuid', 'password' => 'password' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'integer' => 'setInteger', 'int32' => 'setInt32', 'int64' => 'setInt64', @@ -129,18 +125,14 @@ public static function attributeMap() 'date_time' => 'setDateTime', 'uuid' => 'setUuid', 'password' => 'setPassword' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'integer' => 'getInteger', 'int32' => 'getInt32', 'int64' => 'getInt64', @@ -154,7 +146,17 @@ public static function setters() 'date_time' => 'getDateTime', 'uuid' => 'getUuid', 'password' => 'getPassword' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -169,11 +171,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -199,43 +201,54 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); - if ($this->container['integer'] > 100.0) { + $invalid_properties = []; + if (!is_null($this->container['integer']) && ($this->container['integer'] > 100.0)) { $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100.0."; } - if ($this->container['integer'] < 10.0) { + + if (!is_null($this->container['integer']) && ($this->container['integer'] < 10.0)) { $invalid_properties[] = "invalid value for 'integer', must be bigger than or equal to 10.0."; } - if ($this->container['int32'] > 200.0) { + + if (!is_null($this->container['int32']) && ($this->container['int32'] > 200.0)) { $invalid_properties[] = "invalid value for 'int32', must be smaller than or equal to 200.0."; } - if ($this->container['int32'] < 20.0) { + + if (!is_null($this->container['int32']) && ($this->container['int32'] < 20.0)) { $invalid_properties[] = "invalid value for 'int32', must be bigger than or equal to 20.0."; } + if ($this->container['number'] === null) { $invalid_properties[] = "'number' can't be null"; } - if ($this->container['number'] > 543.2) { + if (($this->container['number'] > 543.2)) { $invalid_properties[] = "invalid value for 'number', must be smaller than or equal to 543.2."; } - if ($this->container['number'] < 32.1) { + + if (($this->container['number'] < 32.1)) { $invalid_properties[] = "invalid value for 'number', must be bigger than or equal to 32.1."; } - if ($this->container['float'] > 987.6) { + + if (!is_null($this->container['float']) && ($this->container['float'] > 987.6)) { $invalid_properties[] = "invalid value for 'float', must be smaller than or equal to 987.6."; } - if ($this->container['float'] < 54.3) { + + if (!is_null($this->container['float']) && ($this->container['float'] < 54.3)) { $invalid_properties[] = "invalid value for 'float', must be bigger than or equal to 54.3."; } - if ($this->container['double'] > 123.4) { + + if (!is_null($this->container['double']) && ($this->container['double'] > 123.4)) { $invalid_properties[] = "invalid value for 'double', must be smaller than or equal to 123.4."; } - if ($this->container['double'] < 67.8) { + + if (!is_null($this->container['double']) && ($this->container['double'] < 67.8)) { $invalid_properties[] = "invalid value for 'double', must be bigger than or equal to 67.8."; } - if (!preg_match("/[a-z]/i", $this->container['string'])) { + + if (!is_null($this->container['string']) && !preg_match("/[a-z]/i", $this->container['string'])) { $invalid_properties[] = "invalid value for 'string', must be conform to the pattern /[a-z]/i."; } + if ($this->container['byte'] === null) { $invalid_properties[] = "'byte' can't be null"; } @@ -245,12 +258,14 @@ public function listInvalidProperties() if ($this->container['password'] === null) { $invalid_properties[] = "'password' can't be null"; } - if (strlen($this->container['password']) > 64) { + if ((strlen($this->container['password']) > 64)) { $invalid_properties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; } - if (strlen($this->container['password']) < 10) { + + if ((strlen($this->container['password']) < 10)) { $invalid_properties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; } + return $invalid_properties; } @@ -334,12 +349,13 @@ public function getInteger() public function setInteger($integer) { - if ($integer > 100.0) { + if (!is_null($integer) && ($integer > 100.0)) { throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be smaller than or equal to 100.0.'); } - if ($integer < 10.0) { + if (!is_null($integer) && ($integer < 10.0)) { throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.0.'); } + $this->container['integer'] = $integer; return $this; @@ -362,12 +378,13 @@ public function getInt32() public function setInt32($int32) { - if ($int32 > 200.0) { + if (!is_null($int32) && ($int32 > 200.0)) { throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be smaller than or equal to 200.0.'); } - if ($int32 < 20.0) { + if (!is_null($int32) && ($int32 < 20.0)) { throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.0.'); } + $this->container['int32'] = $int32; return $this; @@ -411,12 +428,13 @@ public function getNumber() public function setNumber($number) { - if ($number > 543.2) { + if (($number > 543.2)) { throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be smaller than or equal to 543.2.'); } - if ($number < 32.1) { + if (($number < 32.1)) { throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be bigger than or equal to 32.1.'); } + $this->container['number'] = $number; return $this; @@ -439,12 +457,13 @@ public function getFloat() public function setFloat($float) { - if ($float > 987.6) { + if (!is_null($float) && ($float > 987.6)) { throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be smaller than or equal to 987.6.'); } - if ($float < 54.3) { + if (!is_null($float) && ($float < 54.3)) { throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be bigger than or equal to 54.3.'); } + $this->container['float'] = $float; return $this; @@ -467,12 +486,13 @@ public function getDouble() public function setDouble($double) { - if ($double > 123.4) { + if (!is_null($double) && ($double > 123.4)) { throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be smaller than or equal to 123.4.'); } - if ($double < 67.8) { + if (!is_null($double) && ($double < 67.8)) { throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be bigger than or equal to 67.8.'); } + $this->container['double'] = $double; return $this; @@ -495,9 +515,10 @@ public function getString() public function setString($string) { - if (!preg_match("/[a-z]/i", $string)) { - throw new \InvalidArgumentException('invalid value for $string when calling FormatTest., must be conform to the pattern /[a-z]/i.'); + if (!is_null($string) && (!preg_match("/[a-z]/i", $string))) { + throw new \InvalidArgumentException("invalid value for $string when calling FormatTest., must conform to the pattern /[a-z]/i."); } + $this->container['string'] = $string; return $this; @@ -624,12 +645,13 @@ public function getPassword() */ public function setPassword($password) { - if (strlen($password) > 64) { + if ((strlen($password) > 64)) { throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be smaller than or equal to 64.'); } - if (strlen($password) < 10) { + if ((strlen($password) < 10)) { throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be bigger than or equal to 10.'); } + $this->container['password'] = $password; return $this; @@ -692,5 +714,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php index 8767cd25093..f8f0e901a76 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * HasOnlyReadOnly Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class HasOnlyReadOnly implements ArrayAccess @@ -65,10 +65,10 @@ class HasOnlyReadOnly implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'bar' => 'string', 'foo' => 'string' - ); + ]; public static function swaggerTypes() { @@ -79,38 +79,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'bar' => 'bar', 'foo' => 'foo' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'bar' => 'setBar', 'foo' => 'setFoo' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'bar' => 'getBar', 'foo' => 'getFoo' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -125,11 +127,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -144,7 +146,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -259,5 +261,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php index dff8b6cbb62..787447c416a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * MapTest Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class MapTest implements ArrayAccess @@ -65,10 +65,10 @@ class MapTest implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'map_map_of_string' => 'map[string,map[string,string]]', 'map_of_enum_string' => 'map[string,string]' - ); + ]; public static function swaggerTypes() { @@ -79,44 +79,48 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'map_map_of_string' => 'map_map_of_string', 'map_of_enum_string' => 'map_of_enum_string' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'map_map_of_string' => 'setMapMapOfString', 'map_of_enum_string' => 'setMapOfEnumString' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'map_map_of_string' => 'getMapMapOfString', 'map_of_enum_string' => 'getMapOfEnumString' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { return self::$getters; } + const MAP_OF_ENUM_STRING_UPPER = 'UPPER'; + const MAP_OF_ENUM_STRING_LOWER = 'lower'; @@ -127,7 +131,8 @@ public static function getters() public function getMapOfEnumStringAllowableValues() { return [ - + self::MAP_OF_ENUM_STRING_UPPER, + self::MAP_OF_ENUM_STRING_LOWER, ]; } @@ -136,11 +141,11 @@ public function getMapOfEnumStringAllowableValues() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -155,11 +160,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); - $allowed_values = array(); - if (!in_array($this->container['map_of_enum_string'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'map_of_enum_string', must be one of #{allowed_values}."; - } + $invalid_properties = []; return $invalid_properties; } @@ -171,10 +172,6 @@ public function listInvalidProperties() */ public function valid() { - $allowed_values = array(); - if (!in_array($this->container['map_of_enum_string'], $allowed_values)) { - return false; - } return true; } @@ -216,9 +213,9 @@ public function getMapOfEnumString() */ public function setMapOfEnumString($map_of_enum_string) { - $allowed_values = array(); - if (!in_array($map_of_enum_string, $allowed_values)) { - throw new \InvalidArgumentException("Invalid value for 'map_of_enum_string', must be one of "); + $allowed_values = array('UPPER', 'lower'); + if (!is_null($map_of_enum_string) && (array_diff($map_of_enum_string, $allowed_values))) { + throw new \InvalidArgumentException("Invalid value for 'map_of_enum_string', must be one of 'UPPER', 'lower'"); } $this->container['map_of_enum_string'] = $map_of_enum_string; @@ -282,5 +279,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 16bd741e91d..3d4bbad56cb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * MixedPropertiesAndAdditionalPropertiesClass Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess @@ -65,11 +65,11 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'uuid' => 'string', 'date_time' => '\DateTime', 'map' => 'map[string,\Swagger\Client\Model\Animal]' - ); + ]; public static function swaggerTypes() { @@ -80,41 +80,43 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'uuid' => 'uuid', 'date_time' => 'dateTime', 'map' => 'map' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'uuid' => 'setUuid', 'date_time' => 'setDateTime', 'map' => 'setMap' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'uuid' => 'getUuid', 'date_time' => 'getDateTime', 'map' => 'getMap' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -129,11 +131,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -149,7 +151,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -285,5 +287,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 04e5f99322d..8dd86b5e5b3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,10 +48,10 @@ * * @category Class */ // @description Model for testing model name starting with number -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Model200Response implements ArrayAccess @@ -66,10 +66,10 @@ class Model200Response implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'name' => 'int', 'class' => 'string' - ); + ]; public static function swaggerTypes() { @@ -80,38 +80,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'name' => 'name', 'class' => 'class' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'name' => 'setName', 'class' => 'setClass' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'name' => 'getName', 'class' => 'getClass' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -126,11 +128,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -145,7 +147,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -260,5 +262,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php new file mode 100644 index 00000000000..885b2dd0417 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -0,0 +1,237 @@ + 'string' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + '_123_list' => '123-list' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + '_123_list' => 'set123List' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + '_123_list' => 'get123List' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['_123_list'] = isset($data['_123_list']) ? $data['_123_list'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets _123_list + * @return string + */ + public function get123List() + { + return $this->container['_123_list']; + } + + /** + * Sets _123_list + * @param string $_123_list + * @return $this + */ + public function set123List($_123_list) + { + $this->container['_123_list'] = $_123_list; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 9e0edd0e426..128d0551db0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,10 +48,10 @@ * * @category Class */ // @description Model for testing reserved words -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelReturn implements ArrayAccess @@ -66,9 +66,9 @@ class ModelReturn implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'return' => 'int' - ); + ]; public static function swaggerTypes() { @@ -79,35 +79,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'return' => 'return' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'return' => 'setReturn' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'return' => 'getReturn' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -122,11 +124,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -140,7 +142,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -234,5 +236,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index 780842932f1..483859c19ef 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,10 +48,10 @@ * * @category Class */ // @description Model for testing model name same as property name -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Name implements ArrayAccess @@ -66,12 +66,12 @@ class Name implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'name' => 'int', 'snake_case' => 'int', 'property' => 'string', '_123_number' => 'int' - ); + ]; public static function swaggerTypes() { @@ -82,44 +82,46 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'name' => 'name', 'snake_case' => 'snake_case', 'property' => 'property', '_123_number' => '123Number' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'name' => 'setName', 'snake_case' => 'setSnakeCase', 'property' => 'setProperty', '_123_number' => 'set123Number' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'name' => 'getName', 'snake_case' => 'getSnakeCase', 'property' => 'getProperty', '_123_number' => 'get123Number' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -134,11 +136,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -155,7 +157,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; if ($this->container['name'] === null) { $invalid_properties[] = "'name' can't be null"; } @@ -318,5 +320,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php index a5c1a292dd0..1012a0cceb8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * NumberOnly Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class NumberOnly implements ArrayAccess @@ -65,9 +65,9 @@ class NumberOnly implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'just_number' => 'float' - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'just_number' => 'JustNumber' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'just_number' => 'setJustNumber' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'just_number' => 'getJustNumber' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -139,7 +141,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -233,5 +235,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 47c29ec67b8..4daa3318040 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Order Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Order implements ArrayAccess @@ -65,14 +65,14 @@ class Order implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'id' => 'int', 'pet_id' => 'int', 'quantity' => 'int', 'ship_date' => '\DateTime', 'status' => 'string', 'complete' => 'bool' - ); + ]; public static function swaggerTypes() { @@ -83,50 +83,52 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'id' => 'id', 'pet_id' => 'petId', 'quantity' => 'quantity', 'ship_date' => 'shipDate', 'status' => 'status', 'complete' => 'complete' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'id' => 'setId', 'pet_id' => 'setPetId', 'quantity' => 'setQuantity', 'ship_date' => 'setShipDate', 'status' => 'setStatus', 'complete' => 'setComplete' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'id' => 'getId', 'pet_id' => 'getPetId', 'quantity' => 'getQuantity', 'ship_date' => 'getShipDate', 'status' => 'getStatus', 'complete' => 'getComplete' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -157,11 +159,11 @@ public function getStatusAllowableValues() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -180,11 +182,12 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); - $allowed_values = array("placed", "approved", "delivered"); + $invalid_properties = []; + $allowed_values = ["placed", "approved", "delivered"]; if (!in_array($this->container['status'], $allowed_values)) { $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } + return $invalid_properties; } @@ -196,7 +199,7 @@ public function listInvalidProperties() */ public function valid() { - $allowed_values = array("placed", "approved", "delivered"); + $allowed_values = ["placed", "approved", "delivered"]; if (!in_array($this->container['status'], $allowed_values)) { return false; } @@ -305,7 +308,7 @@ public function getStatus() public function setStatus($status) { $allowed_values = array('placed', 'approved', 'delivered'); - if (!in_array($status, $allowed_values)) { + if (!is_null($status) && (!in_array($status, $allowed_values))) { throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'placed', 'approved', 'delivered'"); } $this->container['status'] = $status; @@ -391,5 +394,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 3e76cebbae0..bdd0aedae08 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Pet Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Pet implements ArrayAccess @@ -65,14 +65,14 @@ class Pet implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'id' => 'int', 'category' => '\Swagger\Client\Model\Category', 'name' => 'string', 'photo_urls' => 'string[]', 'tags' => '\Swagger\Client\Model\Tag[]', 'status' => 'string' - ); + ]; public static function swaggerTypes() { @@ -83,50 +83,52 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'id' => 'id', 'category' => 'category', 'name' => 'name', 'photo_urls' => 'photoUrls', 'tags' => 'tags', 'status' => 'status' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'id' => 'setId', 'category' => 'setCategory', 'name' => 'setName', 'photo_urls' => 'setPhotoUrls', 'tags' => 'setTags', 'status' => 'setStatus' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'id' => 'getId', 'category' => 'getCategory', 'name' => 'getName', 'photo_urls' => 'getPhotoUrls', 'tags' => 'getTags', 'status' => 'getStatus' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -157,11 +159,11 @@ public function getStatusAllowableValues() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -180,17 +182,18 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; if ($this->container['name'] === null) { $invalid_properties[] = "'name' can't be null"; } if ($this->container['photo_urls'] === null) { $invalid_properties[] = "'photo_urls' can't be null"; } - $allowed_values = array("available", "pending", "sold"); + $allowed_values = ["available", "pending", "sold"]; if (!in_array($this->container['status'], $allowed_values)) { $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } + return $invalid_properties; } @@ -208,7 +211,7 @@ public function valid() if ($this->container['photo_urls'] === null) { return false; } - $allowed_values = array("available", "pending", "sold"); + $allowed_values = ["available", "pending", "sold"]; if (!in_array($this->container['status'], $allowed_values)) { return false; } @@ -338,7 +341,7 @@ public function getStatus() public function setStatus($status) { $allowed_values = array('available', 'pending', 'sold'); - if (!in_array($status, $allowed_values)) { + if (!is_null($status) && (!in_array($status, $allowed_values))) { throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'available', 'pending', 'sold'"); } $this->container['status'] = $status; @@ -403,5 +406,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php index f0021e2965a..44ecad811c4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * ReadOnlyFirst Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ReadOnlyFirst implements ArrayAccess @@ -65,10 +65,10 @@ class ReadOnlyFirst implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'bar' => 'string', 'baz' => 'string' - ); + ]; public static function swaggerTypes() { @@ -79,38 +79,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'bar' => 'bar', 'baz' => 'baz' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'bar' => 'setBar', 'baz' => 'setBaz' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'bar' => 'getBar', 'baz' => 'getBaz' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -125,11 +127,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -144,7 +146,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -259,5 +261,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index a1bb04e5c72..e6a055551f7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * SpecialModelName Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class SpecialModelName implements ArrayAccess @@ -65,9 +65,9 @@ class SpecialModelName implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'special_property_name' => 'int' - ); + ]; public static function swaggerTypes() { @@ -78,35 +78,37 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'special_property_name' => '$special[property.name]' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'special_property_name' => 'setSpecialPropertyName' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'special_property_name' => 'getSpecialPropertyName' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -121,11 +123,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -139,7 +141,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -233,5 +235,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index d1043125e38..cb8c2e0a82b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * Tag Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Tag implements ArrayAccess @@ -65,10 +65,10 @@ class Tag implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'id' => 'int', 'name' => 'string' - ); + ]; public static function swaggerTypes() { @@ -79,38 +79,40 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'id' => 'id', 'name' => 'name' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'id' => 'setId', 'name' => 'setName' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'id' => 'getId', 'name' => 'getName' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -125,11 +127,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -144,7 +146,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -259,5 +261,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 5f1a183d6e5..504eb71204f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,10 +47,10 @@ * User Class Doc Comment * * @category Class */ -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class User implements ArrayAccess @@ -65,7 +65,7 @@ class User implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'id' => 'int', 'username' => 'string', 'first_name' => 'string', @@ -74,7 +74,7 @@ class User implements ArrayAccess 'password' => 'string', 'phone' => 'string', 'user_status' => 'int' - ); + ]; public static function swaggerTypes() { @@ -85,7 +85,7 @@ public static function swaggerTypes() * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'id' => 'id', 'username' => 'username', 'first_name' => 'firstName', @@ -94,18 +94,14 @@ public static function swaggerTypes() 'password' => 'password', 'phone' => 'phone', 'user_status' => 'userStatus' - ); + ]; - public static function attributeMap() - { - return self::$attributeMap; - } /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - protected static $setters = array( + protected static $setters = [ 'id' => 'setId', 'username' => 'setUsername', 'first_name' => 'setFirstName', @@ -114,18 +110,14 @@ public static function attributeMap() 'password' => 'setPassword', 'phone' => 'setPhone', 'user_status' => 'setUserStatus' - ); + ]; - public static function setters() - { - return self::$setters; - } /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - protected static $getters = array( + protected static $getters = [ 'id' => 'getId', 'username' => 'getUsername', 'first_name' => 'getFirstName', @@ -134,7 +126,17 @@ public static function setters() 'password' => 'getPassword', 'phone' => 'getPhone', 'user_status' => 'getUserStatus' - ); + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } public static function getters() { @@ -149,11 +151,11 @@ public static function getters() * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -174,7 +176,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -415,5 +417,3 @@ public function __toString() return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } } - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index ce77aa6c3b3..f1dd03e2056 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,18 +47,17 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializer { - /** * Serialize data * * @param mixed $data the data to serialize * - * @return string serialized form of $data + * @return string|object serialized form of $data */ public static function sanitizeForSerialization($data) { @@ -72,7 +71,7 @@ public static function sanitizeForSerialization($data) } return $data; } elseif (is_object($data)) { - $values = array(); + $values = []; foreach (array_keys($data::swaggerTypes()) as $property) { $getter = $data::getters()[$property]; if ($data->$getter() !== null) { @@ -121,7 +120,7 @@ public function toPathValue($value) * If it's a string, pass through unchanged. It will be url-encoded * later. * - * @param object $object an object to be serialized to a string + * @param string[]|string|\DateTime $object an object to be serialized to a string * * @return string the serialized object */ @@ -153,7 +152,7 @@ public function toHeaderValue($value) * the http body (form parameter). If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the form parameter + * @param string|\SplFileObject $value the value of the form parameter * * @return string the form string */ @@ -171,7 +170,7 @@ public function toFormValue($value) * the parameter. If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the parameter + * @param string|\DateTime $value the value of the parameter * * @return string the header string */ @@ -187,9 +186,10 @@ public function toString($value) /** * Serialize an array to a string. * - * @param array $collection collection to serialize to a string - * @param string $collectionFormat the format use for serialization (csv, + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array * * @return string */ @@ -220,12 +220,12 @@ public function serializeCollection(array $collection, $collectionFormat, $allow /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @param string $httpHeaders HTTP headers - * @param string $discriminator discriminator if polymorphism is used + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used * - * @return object an instance of $class + * @return object|array|null an single or an array of $class instances */ public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { @@ -233,7 +233,7 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi return null; } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); - $deserialized = array(); + $deserialized = []; if (strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; @@ -242,9 +242,9 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi } } return $deserialized; - } elseif (strcasecmp(substr($class, -2), '[]') == 0) { + } elseif (strcasecmp(substr($class, -2), '[]') === 0) { $subClass = substr($class, 0, -2); - $values = array(); + $values = []; foreach ($data as $key => $value) { $values[] = self::deserialize($value, $subClass, null, $discriminator); } @@ -264,7 +264,7 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi } else { return null; } - } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { + } elseif (in_array($class, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { @@ -277,7 +277,6 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); } diff --git a/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist b/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist new file mode 100644 index 00000000000..c12ee148477 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/phpunit.xml.dist @@ -0,0 +1,21 @@ + + + + + ./test/Api + ./test/Model + + + + + + ./lib/Api + ./lib/Model + + + diff --git a/samples/client/petstore/php/SwaggerClient-php/pom.xml b/samples/client/petstore/php/SwaggerClient-php/pom.xml index faaeba82c11..5a0007c898b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/pom.xml +++ b/samples/client/petstore/php/SwaggerClient-php/pom.xml @@ -47,9 +47,6 @@ vendor/bin/phpunit - - test - diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php index 3432b185096..c1ba9f2e8d6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FakeApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php index ab80903b4bc..afc781e543b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class PetApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php index 18146bf0591..c89ff1d23e3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class StoreApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php index def54fa6580..40259040623 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class UserApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php index 5d4028ecf92..c7c90b115d7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -44,7 +44,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClientTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php index 00e17895164..1b008fbb62a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -44,7 +44,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializerTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php index d5150f44b8d..d1b55c88a9d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description AdditionalPropertiesClass * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php index 683e9e5d220..37e736a5d2d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description AnimalFarm * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AnimalFarmTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php index 4890e367f51..c63b5ff4918 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Animal * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AnimalTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php index 8032f2d9149..083f9dcecfd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description ApiResponse * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiResponseTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php index d7c1ddb9cfd..561a8551d1c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description ArrayOfArrayOfNumberOnly * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php index 75da7f819ea..f9c9847ad5b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description ArrayOfNumberOnly * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php index 245abb7641e..1632ff9397f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description ArrayTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayTestTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php index 0d0a876c1a3..ef9f5072fe2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Cat * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class CatTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php index 80394da3493..8a5c3cc8296 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Category * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class CategoryTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php new file mode 100644 index 00000000000..412bd23450d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php @@ -0,0 +1,106 @@ +test_code_inject__end: %s\n" % e + print("Exception when calling FakeApi->test_client_model: %s\n" % e) ``` @@ -68,9 +69,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**test_code_inject__end**](docs/FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ =end +*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_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -104,11 +105,14 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) + - [Client](docs/Client.md) - [Dog](docs/Dog.md) + - [EnumArrays](docs/EnumArrays.md) - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) - [FormatTest](docs/FormatTest.md) - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) @@ -132,6 +136,10 @@ Class | Method | HTTP request | Description - **API key parameter name**: api_key - **Location**: HTTP header +## http_basic_test + +- **Type**: HTTP basic authentication + ## petstore_auth - **Type**: OAuth diff --git a/samples/client/petstore/python/docs/ArrayTest.md b/samples/client/petstore/python/docs/ArrayTest.md index 902710efe0e..6ab0d137806 100644 --- a/samples/client/petstore/python/docs/ArrayTest.md +++ b/samples/client/petstore/python/docs/ArrayTest.md @@ -6,7 +6,6 @@ Name | Type | Description | Notes **array_of_string** | **list[str]** | | [optional] **array_array_of_integer** | **list[list[int]]** | | [optional] **array_array_of_model** | **list[list[ReadOnlyFirst]]** | | [optional] -**array_of_enum** | **list[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/Client.md b/samples/client/petstore/python/docs/Client.md new file mode 100644 index 00000000000..88e99384f92 --- /dev/null +++ b/samples/client/petstore/python/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **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/EnumArrays.md b/samples/client/petstore/python/docs/EnumArrays.md new file mode 100644 index 00000000000..e15a5f1fd04 --- /dev/null +++ b/samples/client/petstore/python/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **str** | | [optional] +**array_enum** | **list[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/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 2f670f5e26f..c6ed3ccfbfc 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -4,18 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject__end**](FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ =end +[**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_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -# **test_code_inject__end** -> test_code_inject__end(test_code_inject__end=test_code_inject__end) +# **test_client_model** +> Client test_client_model(body) -To test code injection */ =end +To test \"client\" model ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -23,24 +24,25 @@ from pprint import pprint # create an instance of the API class api_instance = petstore_api.FakeApi() -test_code_inject__end = 'test_code_inject__end_example' # str | To test code injection */ =end (optional) +body = petstore_api.Client() # Client | client model try: - # To test code injection */ =end - api_instance.test_code_inject__end(test_code_inject__end=test_code_inject__end) + # To test \"client\" model + api_response = api_instance.test_client_model(body) + pprint(api_response) except ApiException as e: - print "Exception when calling FakeApi->test_code_inject__end: %s\n" % e + print("Exception when calling FakeApi->test_client_model: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test_code_inject__end** | **str**| To test code injection */ =end | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -void (empty response body) +[**Client**](Client.md) ### Authorization @@ -48,13 +50,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **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) # **test_endpoint_parameters** -> test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) +> 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) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -62,31 +64,38 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException from pprint import pprint +# Configure HTTP basic authorization: http_basic_test +petstore_api.configuration.username = 'YOUR_USERNAME' +petstore_api.configuration.password = 'YOUR_PASSWORD' + # create an instance of the API class api_instance = petstore_api.FakeApi() number = 3.4 # float | None double = 1.2 # float | None -string = 'string_example' # str | None +pattern_without_delimiter = 'pattern_without_delimiter_example' # str | None byte = 'B' # str | None integer = 56 # int | None (optional) int32 = 56 # int | None (optional) int64 = 789 # int | None (optional) float = 3.4 # float | None (optional) +string = 'string_example' # str | None (optional) binary = 'B' # str | None (optional) date = '2013-10-20' # date | None (optional) 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: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) + 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: - print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) ``` ### Parameters @@ -95,16 +104,18 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **float**| None | **double** | **float**| None | - **string** | **str**| None | + **pattern_without_delimiter** | **str**| None | **byte** | **str**| None | **integer** | **int**| None | [optional] **int32** | **int**| None | [optional] **int64** | **int**| None | [optional] **float** | **float**| None | [optional] + **string** | **str**| None | [optional] **binary** | **str**| None | [optional] **date** | **date**| None | [optional] **date_time** | **datetime**| None | [optional] **password** | **str**| None | [optional] + **param_callback** | **str**| None | [optional] ### Return type @@ -112,7 +123,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -121,13 +132,14 @@ 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_enum_query_parameters** -> test_enum_query_parameters(enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) +# **test_enum_parameters** +> test_enum_parameters(enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string, enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) -To test enum query parameters +To test enum parameters ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -135,21 +147,31 @@ from pprint import pprint # create an instance of the API class api_instance = petstore_api.FakeApi() +enum_form_string_array = ['enum_form_string_array_example'] # list[str] | Form parameter enum test (string array) (optional) +enum_form_string = '-efg' # str | Form parameter enum test (string) (optional) (default to -efg) +enum_header_string_array = ['enum_header_string_array_example'] # list[str] | Header parameter enum test (string array) (optional) +enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) (default to -efg) +enum_query_string_array = ['enum_query_string_array_example'] # list[str] | Query parameter enum test (string array) (optional) enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) (default to -efg) enum_query_integer = 3.4 # float | Query parameter enum test (double) (optional) enum_query_double = 1.2 # float | Query parameter enum test (double) (optional) try: - # To test enum query parameters - api_instance.test_enum_query_parameters(enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) + # 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: - print "Exception when calling FakeApi->test_enum_query_parameters: %s\n" % e + print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**list[str]**](str.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **str**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**list[str]**](str.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **str**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**list[str]**](str.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **str**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **float**| Query parameter enum test (double) | [optional] **enum_query_double** | **float**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/python/docs/List.md b/samples/client/petstore/python/docs/List.md new file mode 100644 index 00000000000..11f4f3a05f3 --- /dev/null +++ b/samples/client/petstore/python/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **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/MapTest.md b/samples/client/petstore/python/docs/MapTest.md index 3e71b5130d7..63cdab0374a 100644 --- a/samples/client/petstore/python/docs/MapTest.md +++ b/samples/client/petstore/python/docs/MapTest.md @@ -4,7 +4,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_map_of_string** | [**dict(str, dict(str, str))**](dict.md) | | [optional] -**map_map_of_enum** | [**dict(str, dict(str, str))**](dict.md) | | [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 109b264942f..553c8152138 100644 --- a/samples/client/petstore/python/docs/PetApi.md +++ b/samples/client/petstore/python/docs/PetApi.md @@ -23,6 +23,7 @@ Add a new pet to the store ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -39,7 +40,7 @@ try: # Add a new pet to the store api_instance.add_pet(body) except ApiException as e: - print "Exception when calling PetApi->add_pet: %s\n" % e + print("Exception when calling PetApi->add_pet: %s\n" % e) ``` ### Parameters @@ -72,6 +73,7 @@ Deletes a pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -89,7 +91,7 @@ try: # Deletes a pet api_instance.delete_pet(pet_id, api_key=api_key) except ApiException as e: - print "Exception when calling PetApi->delete_pet: %s\n" % e + print("Exception when calling PetApi->delete_pet: %s\n" % e) ``` ### Parameters @@ -123,6 +125,7 @@ Multiple status values can be provided with comma separated strings ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -140,7 +143,7 @@ try: api_response = api_instance.find_pets_by_status(status) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->find_pets_by_status: %s\n" % e + print("Exception when calling PetApi->find_pets_by_status: %s\n" % e) ``` ### Parameters @@ -173,6 +176,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -190,7 +194,7 @@ try: api_response = api_instance.find_pets_by_tags(tags) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->find_pets_by_tags: %s\n" % e + print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e) ``` ### Parameters @@ -223,6 +227,7 @@ Returns a single pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -242,7 +247,7 @@ try: api_response = api_instance.get_pet_by_id(pet_id) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->get_pet_by_id: %s\n" % e + print("Exception when calling PetApi->get_pet_by_id: %s\n" % e) ``` ### Parameters @@ -275,6 +280,7 @@ Update an existing pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -291,7 +297,7 @@ try: # Update an existing pet api_instance.update_pet(body) except ApiException as e: - print "Exception when calling PetApi->update_pet: %s\n" % e + print("Exception when calling PetApi->update_pet: %s\n" % e) ``` ### Parameters @@ -324,6 +330,7 @@ Updates a pet in the store with form data ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -342,7 +349,7 @@ 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: - print "Exception when calling PetApi->update_pet_with_form: %s\n" % e + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) ``` ### Parameters @@ -377,6 +384,7 @@ uploads an image ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -396,7 +404,7 @@ try: api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->upload_file: %s\n" % e + print("Exception when calling PetApi->upload_file: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md index 6b71a78659d..54007c9e8e7 100644 --- a/samples/client/petstore/python/docs/StoreApi.md +++ b/samples/client/petstore/python/docs/StoreApi.md @@ -19,6 +19,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -32,7 +33,7 @@ try: # Delete purchase order by ID api_instance.delete_order(order_id) except ApiException as e: - print "Exception when calling StoreApi->delete_order: %s\n" % e + print("Exception when calling StoreApi->delete_order: %s\n" % e) ``` ### Parameters @@ -65,6 +66,7 @@ Returns a map of status codes to quantities ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -83,7 +85,7 @@ try: api_response = api_instance.get_inventory() pprint(api_response) except ApiException as e: - print "Exception when calling StoreApi->get_inventory: %s\n" % e + print("Exception when calling StoreApi->get_inventory: %s\n" % e) ``` ### Parameters @@ -113,6 +115,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -127,7 +130,7 @@ try: api_response = api_instance.get_order_by_id(order_id) pprint(api_response) except ApiException as e: - print "Exception when calling StoreApi->get_order_by_id: %s\n" % e + print("Exception when calling StoreApi->get_order_by_id: %s\n" % e) ``` ### Parameters @@ -160,6 +163,7 @@ Place an order for a pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -174,7 +178,7 @@ try: api_response = api_instance.place_order(body) pprint(api_response) except ApiException as e: - print "Exception when calling StoreApi->place_order: %s\n" % e + print("Exception when calling StoreApi->place_order: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python/docs/UserApi.md index 4009418b13c..8c48c02d7a7 100644 --- a/samples/client/petstore/python/docs/UserApi.md +++ b/samples/client/petstore/python/docs/UserApi.md @@ -23,6 +23,7 @@ This can only be done by the logged in user. ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -36,7 +37,7 @@ try: # Create user api_instance.create_user(body) except ApiException as e: - print "Exception when calling UserApi->create_user: %s\n" % e + print("Exception when calling UserApi->create_user: %s\n" % e) ``` ### Parameters @@ -69,6 +70,7 @@ Creates list of users with given input array ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -82,7 +84,7 @@ try: # Creates list of users with given input array api_instance.create_users_with_array_input(body) except ApiException as e: - print "Exception when calling UserApi->create_users_with_array_input: %s\n" % e + print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e) ``` ### Parameters @@ -115,6 +117,7 @@ Creates list of users with given input array ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -128,7 +131,7 @@ try: # Creates list of users with given input array api_instance.create_users_with_list_input(body) except ApiException as e: - print "Exception when calling UserApi->create_users_with_list_input: %s\n" % e + print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e) ``` ### Parameters @@ -161,6 +164,7 @@ This can only be done by the logged in user. ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -174,7 +178,7 @@ try: # Delete user api_instance.delete_user(username) except ApiException as e: - print "Exception when calling UserApi->delete_user: %s\n" % e + print("Exception when calling UserApi->delete_user: %s\n" % e) ``` ### Parameters @@ -207,6 +211,7 @@ Get user by user name ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -221,7 +226,7 @@ try: api_response = api_instance.get_user_by_name(username) pprint(api_response) except ApiException as e: - print "Exception when calling UserApi->get_user_by_name: %s\n" % e + print("Exception when calling UserApi->get_user_by_name: %s\n" % e) ``` ### Parameters @@ -254,6 +259,7 @@ Logs user into the system ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -269,7 +275,7 @@ try: api_response = api_instance.login_user(username, password) pprint(api_response) except ApiException as e: - print "Exception when calling UserApi->login_user: %s\n" % e + print("Exception when calling UserApi->login_user: %s\n" % e) ``` ### Parameters @@ -303,6 +309,7 @@ Logs out current logged in user session ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -315,7 +322,7 @@ try: # Logs out current logged in user session api_instance.logout_user() except ApiException as e: - print "Exception when calling UserApi->logout_user: %s\n" % e + print("Exception when calling UserApi->logout_user: %s\n" % e) ``` ### Parameters @@ -345,6 +352,7 @@ This can only be done by the logged in user. ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -359,7 +367,7 @@ try: # Updated user api_instance.update_user(username, body) except ApiException as e: - print "Exception when calling UserApi->update_user: %s\n" % e + print("Exception when calling UserApi->update_user: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py index 650b1db0399..8f043d8a1ad 100644 --- a/samples/client/petstore/python/petstore_api/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -34,11 +34,14 @@ from .models.array_test import ArrayTest from .models.cat import Cat from .models.category import Category +from .models.client import Client from .models.dog import Dog +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 diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index 2521ba15fd3..adf66173dbc 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -19,17 +19,15 @@ """ from __future__ import absolute_import + from . import models from .rest import RESTClientObject from .rest import ApiException import os import re -import sys -import urllib import json import mimetypes -import random import tempfile import threading @@ -37,14 +35,8 @@ from datetime import date # python 2 and python 3 compatibility library -from six import iteritems - -try: - # for python3 - from urllib.parse import quote -except ImportError: - # for python2 - from urllib import quote +from six import PY3, integer_types, iteritems, text_type +from six.moves.urllib.parse import quote from .configuration import Configuration @@ -103,34 +95,40 @@ def set_default_header(self, 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, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): - # headers parameters + # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.\ - replace('{' + k + '}', replacement) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + resource_path = resource_path.replace( + '{%s}' % k, quote(str(v))) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) - for k, v in iteritems(query_params)} + query_params = self.parameters_to_tuples(query_params, + collection_formats) # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) @@ -159,31 +157,16 @@ def __call_api(self, resource_path, method, if callback: callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return ( deserialized_data ); + return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - - - def to_path_value(self, obj): - """ - Takes value and turn it into a string suitable for inclusion in - the path, by url-encoding. - - :param obj: object or string value. - - :return string: quoted value. - """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) def sanitize_for_serialization(self, obj): """ Builds a JSON POST object. If obj is None, return None. - If obj is str, int, float, bool, return directly. + If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. @@ -193,9 +176,7 @@ def sanitize_for_serialization(self, obj): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, float, bool, tuple) - if sys.version_info < (3, 0): - types = types + (unicode,) + types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -203,6 +184,9 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: @@ -227,7 +211,7 @@ def deserialize(self, response, response_type): :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name. + deserialized object, or string of class name. :return: deserialized object. """ @@ -272,11 +256,13 @@ def __deserialize(self, data, klass): if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) + elif klass == 'long': + klass = int if PY3 else long # for model types else: klass = eval('models.' + klass) - if klass in [int, float, str, bool]: + if klass in integer_types or klass in (float, str, bool): return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -290,7 +276,8 @@ def __deserialize(self, data, klass): 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, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -312,6 +299,8 @@ def call_api(self, resource_path, method, If provide this parameter, the request will be called asynchronously. :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. :return: If provide parameter callback, the request will be called asynchronously. @@ -323,7 +312,8 @@ def call_api(self, resource_path, method, return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, - response_type, auth_settings, callback, _return_http_data_only) + response_type, auth_settings, callback, + _return_http_data_only, collection_formats) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -331,7 +321,8 @@ def call_api(self, resource_path, method, header_params, body, post_params, files, response_type, auth_settings, - callback,_return_http_data_only)) + callback, _return_http_data_only, + collection_formats)) thread.start() return thread @@ -379,10 +370,41 @@ def request(self, method, url, query_params=None, headers=None, body=body) else: raise ValueError( - "http method must be `GET`, `HEAD`," + "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) + def parameters_to_tuples(self, params, collection_formats): + """ + 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 + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in iteritems(params) if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. @@ -450,7 +472,7 @@ def update_params_for_auth(self, headers, querys, auth_settings): Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. """ config = Configuration() @@ -466,7 +488,7 @@ def update_params_for_auth(self, headers, querys, auth_settings): elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + querys.append((auth_setting['key'], auth_setting['value'])) else: raise ValueError( 'Authentication token must be in `query` or `header`' @@ -505,7 +527,7 @@ def __deserialize_primitive(self, data, klass): :param data: str. :param klass: class literal. - :return: int, float, str, bool. + :return: int, long, float, str, bool. """ try: value = klass(data) @@ -573,6 +595,9 @@ def __deserialize_model(self, data, klass): """ instance = klass() + if not instance.swagger_types: + return data + for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index df4838bde82..944396a9fdc 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -51,9 +51,9 @@ def __init__(self, api_client=None): config.api_client = ApiClient() self.api_client = config.api_client - def test_code_inject__end(self, **kwargs): + def test_client_model(self, body, **kwargs): """ - To test code injection */ =end + To test \"client\" model This method makes a synchronous HTTP request by default. To make an @@ -62,25 +62,25 @@ def test_code_inject__end(self, **kwargs): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_code_inject__end(callback=callback_function) + >>> thread = api.test_client_model(body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) - :param str test_code_inject__end: To test code injection */ =end - :return: None + :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_code_inject__end_with_http_info(**kwargs) + return self.test_client_model_with_http_info(body, **kwargs) else: - (data) = self.test_code_inject__end_with_http_info(**kwargs) + (data) = self.test_client_model_with_http_info(body, **kwargs) return data - def test_code_inject__end_with_http_info(self, **kwargs): + def test_client_model_with_http_info(self, body, **kwargs): """ - To test code injection */ =end + To test \"client\" model This method makes a synchronous HTTP request by default. To make an @@ -89,17 +89,17 @@ def test_code_inject__end_with_http_info(self, **kwargs): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_code_inject__end_with_http_info(callback=callback_function) + >>> thread = api.test_client_model_with_http_info(body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) - :param str test_code_inject__end: To test code injection */ =end - :return: None + :param Client body: client model (required) + :return: Client If the method is called asynchronously, returns the request thread. """ - all_params = ['test_code_inject__end'] + all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') @@ -108,10 +108,16 @@ def test_code_inject__end_with_http_info(self, **kwargs): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method test_code_inject__end" % key + " to method test_client_model" % 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_client_model`") + + + collection_formats = {} resource_path = '/fake'.replace('{format}', 'json') path_params = {} @@ -122,37 +128,38 @@ def test_code_inject__end_with_http_info(self, **kwargs): form_params = [] local_var_files = {} - if 'test_code_inject__end' in params: - form_params.append(('test code inject */ =end', params['test_code_inject__end'])) 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', '*/ end']) + select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', '*/ =end));(phpinfo(']) + select_header_content_type(['application/json']) # Authentication setting auth_settings = [] - return self.api_client.call_api(resource_path, 'PUT', + 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=None, + response_type='Client', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) - def test_endpoint_parameters(self, number, double, string, byte, **kwargs): + def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -163,34 +170,36 @@ def test_endpoint_parameters(self, number, double, string, byte, **kwargs): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_endpoint_parameters(number, double, string, byte, callback=callback_function) + >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param float number: None (required) :param float double: None (required) - :param str string: None (required) + :param str pattern_without_delimiter: None (required) :param str byte: None (required) :param int integer: None :param int int32: None :param int int64: None :param float float: None + :param str string: None :param str binary: None :param date date: None :param datetime date_time: None :param str password: None + :param str param_callback: None :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): - return self.test_endpoint_parameters_with_http_info(number, double, string, byte, **kwargs) + return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) else: - (data) = self.test_endpoint_parameters_with_http_info(number, double, string, byte, **kwargs) + (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) return data - def test_endpoint_parameters_with_http_info(self, number, double, string, byte, **kwargs): + 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 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -201,28 +210,30 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_endpoint_parameters_with_http_info(number, double, string, byte, callback=callback_function) + >>> thread = api.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param float number: None (required) :param float double: None (required) - :param str string: None (required) + :param str pattern_without_delimiter: None (required) :param str byte: None (required) :param int integer: None :param int int32: None :param int int64: None :param float float: None + :param str string: None :param str binary: None :param date date: None :param datetime date_time: None :param str password: None + :param str param_callback: None :return: None If the method is called asynchronously, returns the request thread. """ - all_params = ['number', 'double', 'string', 'byte', 'integer', 'int32', 'int64', 'float', 'binary', 'date', 'date_time', 'password'] + all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] all_params.append('callback') all_params.append('_return_http_data_only') @@ -241,37 +252,42 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, # 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`") - # verify the required parameter 'string' is set - if ('string' not in params) or (params['string'] is None): - raise ValueError("Missing the required parameter `string` when calling `test_endpoint_parameters`") + # 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`") # 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`") + 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`") + 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 '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 '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.0: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") if 'integer' in params and params['integer'] < 10.0: raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") if 'int32' in params and params['int32'] > 200.0: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") if 'int32' in params and params['int32'] < 20.0: raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") if 'float' in params and params['float'] > 987.6: - raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `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`") + + collection_formats = {} + resource_path = '/fake'.replace('{format}', 'json') path_params = {} @@ -295,6 +311,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, form_params.append(('double', params['double'])) if 'string' in params: form_params.append(('string', params['string'])) + if 'pattern_without_delimiter' in params: + form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) if 'byte' in params: form_params.append(('byte', params['byte'])) if 'binary' in params: @@ -305,6 +323,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, form_params.append(('dateTime', params['date_time'])) if 'password' in params: form_params.append(('password', params['password'])) + if 'param_callback' in params: + form_params.append(('callback', params['param_callback'])) body_params = None @@ -319,7 +339,7 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # Authentication setting - auth_settings = [] + auth_settings = ['http_basic_test'] return self.api_client.call_api(resource_path, 'POST', path_params, @@ -331,11 +351,12 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) - def test_enum_query_parameters(self, **kwargs): + def test_enum_parameters(self, **kwargs): """ - To test enum query parameters + To test enum parameters This method makes a synchronous HTTP request by default. To make an @@ -344,10 +365,15 @@ def test_enum_query_parameters(self, **kwargs): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_enum_query_parameters(callback=callback_function) + >>> thread = api.test_enum_parameters(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) + :param list[str] enum_form_string_array: Form parameter enum test (string array) + :param str enum_form_string: Form parameter enum test (string) + :param list[str] enum_header_string_array: Header parameter enum test (string array) + :param str enum_header_string: Header parameter enum test (string) + :param list[str] enum_query_string_array: Query parameter enum test (string array) :param str enum_query_string: Query parameter enum test (string) :param float enum_query_integer: Query parameter enum test (double) :param float enum_query_double: Query parameter enum test (double) @@ -357,14 +383,14 @@ def test_enum_query_parameters(self, **kwargs): """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): - return self.test_enum_query_parameters_with_http_info(**kwargs) + return self.test_enum_parameters_with_http_info(**kwargs) else: - (data) = self.test_enum_query_parameters_with_http_info(**kwargs) + (data) = self.test_enum_parameters_with_http_info(**kwargs) return data - def test_enum_query_parameters_with_http_info(self, **kwargs): + def test_enum_parameters_with_http_info(self, **kwargs): """ - To test enum query parameters + To test enum parameters This method makes a synchronous HTTP request by default. To make an @@ -373,10 +399,15 @@ def test_enum_query_parameters_with_http_info(self, **kwargs): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_enum_query_parameters_with_http_info(callback=callback_function) + >>> thread = api.test_enum_parameters_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) + :param list[str] enum_form_string_array: Form parameter enum test (string array) + :param str enum_form_string: Form parameter enum test (string) + :param list[str] enum_header_string_array: Header parameter enum test (string array) + :param str enum_header_string: Header parameter enum test (string) + :param list[str] enum_query_string_array: Query parameter enum test (string array) :param str enum_query_string: Query parameter enum test (string) :param float enum_query_integer: Query parameter enum test (double) :param float enum_query_double: Query parameter enum test (double) @@ -385,7 +416,7 @@ def test_enum_query_parameters_with_http_info(self, **kwargs): returns the request thread. """ - all_params = ['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'] all_params.append('callback') all_params.append('_return_http_data_only') @@ -394,24 +425,40 @@ def test_enum_query_parameters_with_http_info(self, **kwargs): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method test_enum_query_parameters" % key + " to method test_enum_parameters" % key ) params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/fake'.replace('{format}', 'json') path_params = {} query_params = {} + if 'enum_query_string_array' in params: + query_params['enum_query_string_array'] = params['enum_query_string_array'] + collection_formats['enum_query_string_array'] = 'csv' + if 'enum_query_string' in params: + query_params['enum_query_string'] = params['enum_query_string'] if 'enum_query_integer' in params: query_params['enum_query_integer'] = params['enum_query_integer'] 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' + if 'enum_header_string' in params: + header_params['enum_header_string'] = params['enum_header_string'] form_params = [] local_var_files = {} - if 'enum_query_string' in params: - form_params.append(('enum_query_string', params['enum_query_string'])) + 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' + if 'enum_form_string' in params: + form_params.append(('enum_form_string', params['enum_form_string'])) if 'enum_query_double' in params: form_params.append(('enum_query_double', params['enum_query_double'])) @@ -440,4 +487,5 @@ def test_enum_query_parameters_with_http_info(self, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index a186727b958..b0aa2d9a842 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -116,6 +116,9 @@ def add_pet_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `add_pet`") + + collection_formats = {} + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -153,7 +156,8 @@ def add_pet_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def delete_pet(self, pet_id, **kwargs): """ @@ -222,6 +226,9 @@ def delete_pet_with_http_info(self, pet_id, **kwargs): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -261,7 +268,8 @@ def delete_pet_with_http_info(self, pet_id, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def find_pets_by_status(self, status, **kwargs): """ @@ -328,12 +336,16 @@ def find_pets_by_status_with_http_info(self, status, **kwargs): if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") + + collection_formats = {} + resource_path = '/pet/findByStatus'.replace('{format}', 'json') path_params = {} query_params = {} if 'status' in params: query_params['status'] = params['status'] + collection_formats['status'] = 'csv' header_params = {} @@ -365,7 +377,8 @@ def find_pets_by_status_with_http_info(self, status, **kwargs): response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def find_pets_by_tags(self, tags, **kwargs): """ @@ -432,12 +445,16 @@ def find_pets_by_tags_with_http_info(self, tags, **kwargs): if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") + + collection_formats = {} + resource_path = '/pet/findByTags'.replace('{format}', 'json') path_params = {} query_params = {} if 'tags' in params: query_params['tags'] = params['tags'] + collection_formats['tags'] = 'csv' header_params = {} @@ -469,7 +486,8 @@ def find_pets_by_tags_with_http_info(self, tags, **kwargs): response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_pet_by_id(self, pet_id, **kwargs): """ @@ -536,6 +554,9 @@ def get_pet_by_id_with_http_info(self, pet_id, **kwargs): 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`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -573,7 +594,8 @@ def get_pet_by_id_with_http_info(self, pet_id, **kwargs): response_type='Pet', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def update_pet(self, body, **kwargs): """ @@ -640,6 +662,9 @@ def update_pet_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_pet`") + + collection_formats = {} + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -677,7 +702,8 @@ def update_pet_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def update_pet_with_form(self, pet_id, **kwargs): """ @@ -748,6 +774,9 @@ def update_pet_with_form_with_http_info(self, pet_id, **kwargs): 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`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -789,7 +818,8 @@ def update_pet_with_form_with_http_info(self, pet_id, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def upload_file(self, pet_id, **kwargs): """ @@ -860,6 +890,9 @@ def upload_file_with_http_info(self, pet_id, **kwargs): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + + collection_formats = {} + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -901,4 +934,5 @@ def upload_file_with_http_info(self, pet_id, **kwargs): response_type='ApiResponse', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index e5e972c7444..c7f37de09e8 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -118,6 +118,9 @@ def delete_order_with_http_info(self, order_id, **kwargs): if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `delete_order`, must be a value greater than or equal to `1.0`") + + collection_formats = {} + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -155,7 +158,8 @@ def delete_order_with_http_info(self, order_id, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_inventory(self, **kwargs): """ @@ -217,6 +221,9 @@ def get_inventory_with_http_info(self, **kwargs): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -252,7 +259,8 @@ def get_inventory_with_http_info(self, **kwargs): response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_order_by_id(self, order_id, **kwargs): """ @@ -320,9 +328,12 @@ def get_order_by_id_with_http_info(self, order_id, **kwargs): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") if 'order_id' in params and params['order_id'] > 5.0: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") + + collection_formats = {} + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -360,7 +371,8 @@ def get_order_by_id_with_http_info(self, order_id, **kwargs): response_type='Order', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def place_order(self, body, **kwargs): """ @@ -427,6 +439,9 @@ def place_order_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `place_order`") + + collection_formats = {} + resource_path = '/store/order'.replace('{format}', 'json') path_params = {} @@ -464,4 +479,5 @@ def place_order_with_http_info(self, body, **kwargs): response_type='Order', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py index 57e89ccca3d..cc7f2d35083 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -116,6 +116,9 @@ def create_user_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_user`") + + collection_formats = {} + resource_path = '/user'.replace('{format}', 'json') path_params = {} @@ -153,7 +156,8 @@ def create_user_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def create_users_with_array_input(self, body, **kwargs): """ @@ -220,6 +224,9 @@ def create_users_with_array_input_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") + + collection_formats = {} + resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -257,7 +264,8 @@ def create_users_with_array_input_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def create_users_with_list_input(self, body, **kwargs): """ @@ -324,6 +332,9 @@ def create_users_with_list_input_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") + + collection_formats = {} + resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -361,7 +372,8 @@ def create_users_with_list_input_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def delete_user(self, username, **kwargs): """ @@ -428,6 +440,9 @@ def delete_user_with_http_info(self, username, **kwargs): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `delete_user`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -465,7 +480,8 @@ def delete_user_with_http_info(self, username, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_user_by_name(self, username, **kwargs): """ @@ -532,6 +548,9 @@ def get_user_by_name_with_http_info(self, username, **kwargs): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -569,7 +588,8 @@ def get_user_by_name_with_http_info(self, username, **kwargs): response_type='User', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def login_user(self, username, password, **kwargs): """ @@ -641,6 +661,9 @@ def login_user_with_http_info(self, username, password, **kwargs): if ('password' not in params) or (params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `login_user`") + + collection_formats = {} + resource_path = '/user/login'.replace('{format}', 'json') path_params = {} @@ -680,7 +703,8 @@ def login_user_with_http_info(self, username, password, **kwargs): response_type='str', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def logout_user(self, **kwargs): """ @@ -742,6 +766,9 @@ def logout_user_with_http_info(self, **kwargs): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -777,7 +804,8 @@ def logout_user_with_http_info(self, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def update_user(self, username, body, **kwargs): """ @@ -849,6 +877,9 @@ def update_user_with_http_info(self, username, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_user`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -888,4 +919,5 @@ def update_user_with_http_info(self, username, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + 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 45cfef15472..d2f3b06a558 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -23,19 +23,14 @@ """ from __future__ import absolute_import -import base64 -import urllib3 -try: - import httplib -except ImportError: - # for python3 - import http.client as httplib +import urllib3 import sys import logging from six import iteritems +from six.moves import http_client as httplib def singleton(cls, *args, **kw): @@ -228,8 +223,15 @@ def auth_settings(self): 'key': 'api_key', 'value': self.get_api_key_with_prefix('api_key') }, + 'http_basic_test': + { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + }, - 'petstore_auth': + 'petstore_auth': { 'type': 'oauth2', 'in': 'header', diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py index 56620212e46..ac0530ef190 100644 --- a/samples/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -34,11 +34,14 @@ from .array_test import ArrayTest from .cat import Cat from .category import Category +from .client import Client from .dog import Dog +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 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 8686db9210f..ff0a3565135 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 @@ -54,6 +54,7 @@ def __init__(self, map_property=None, map_of_map_property=None): self._map_property = map_property self._map_of_map_property = map_of_map_property + @property def map_property(self): """ diff --git a/samples/client/petstore/python/petstore_api/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py index 6c20ff3208f..23bcbe07457 100644 --- a/samples/client/petstore/python/petstore_api/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -54,6 +54,7 @@ def __init__(self, class_name=None, color='red'): self._class_name = class_name self._color = color + @property def class_name(self): """ @@ -74,6 +75,8 @@ def class_name(self, class_name): :param class_name: The class_name of this Animal. :type: str """ + if class_name is None: + raise ValueError("Invalid value for `class_name`, must not be `None`") self._class_name = class_name 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 3a3a40ccea4..b14127d636e 100644 --- a/samples/client/petstore/python/petstore_api/models/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/models/animal_farm.py @@ -49,6 +49,7 @@ def __init__(self): } + def to_dict(self): """ Returns the model properties as a dict 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 7540b7a323c..76595db023b 100644 --- a/samples/client/petstore/python/petstore_api/models/api_response.py +++ b/samples/client/petstore/python/petstore_api/models/api_response.py @@ -57,6 +57,7 @@ def __init__(self, code=None, type=None, message=None): self._type = type self._message = message + @property def code(self): """ 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 0cbf47edc36..15c57560625 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 @@ -51,6 +51,7 @@ def __init__(self, array_array_number=None): self._array_array_number = array_array_number + @property def array_array_number(self): """ 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 27e60c1808f..9a8576f070d 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 @@ -51,6 +51,7 @@ def __init__(self, array_number=None): self._array_number = array_number + @property def array_number(self): """ 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 5a6813b60eb..3066c365cad 100644 --- a/samples/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -32,7 +32,7 @@ class ArrayTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None, array_of_enum=None): + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): """ ArrayTest - a model defined in Swagger @@ -44,21 +44,19 @@ def __init__(self, array_of_string=None, array_array_of_integer=None, array_arra self.swagger_types = { 'array_of_string': 'list[str]', 'array_array_of_integer': 'list[list[int]]', - 'array_array_of_model': 'list[list[ReadOnlyFirst]]', - 'array_of_enum': 'list[str]' + 'array_array_of_model': 'list[list[ReadOnlyFirst]]' } self.attribute_map = { 'array_of_string': 'array_of_string', 'array_array_of_integer': 'array_array_of_integer', - 'array_array_of_model': 'array_array_of_model', - 'array_of_enum': 'array_of_enum' + 'array_array_of_model': 'array_array_of_model' } self._array_of_string = array_of_string self._array_array_of_integer = array_array_of_integer self._array_array_of_model = array_array_of_model - self._array_of_enum = array_of_enum + @property def array_of_string(self): @@ -129,35 +127,6 @@ def array_array_of_model(self, array_array_of_model): self._array_array_of_model = array_array_of_model - @property - def array_of_enum(self): - """ - Gets the array_of_enum of this ArrayTest. - - - :return: The array_of_enum of this ArrayTest. - :rtype: list[str] - """ - return self._array_of_enum - - @array_of_enum.setter - def array_of_enum(self, array_of_enum): - """ - Sets the array_of_enum of this ArrayTest. - - - :param array_of_enum: The array_of_enum of this ArrayTest. - :type: list[str] - """ - allowed_values = [] - if array_of_enum not in allowed_values: - raise ValueError( - "Invalid value for `array_of_enum`, must be one of {0}" - .format(allowed_values) - ) - - self._array_of_enum = array_of_enum - def to_dict(self): """ Returns the model properties as a dict diff --git a/samples/client/petstore/python/petstore_api/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py index 77fdc9e23bf..361d5d091ae 100644 --- a/samples/client/petstore/python/petstore_api/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -57,6 +57,7 @@ def __init__(self, class_name=None, color='red', declawed=None): self._color = color self._declawed = declawed + @property def class_name(self): """ @@ -77,6 +78,8 @@ def class_name(self, class_name): :param class_name: The class_name of this Cat. :type: str """ + if class_name is None: + raise ValueError("Invalid value for `class_name`, must not be `None`") self._class_name = class_name diff --git a/samples/client/petstore/python/petstore_api/models/category.py b/samples/client/petstore/python/petstore_api/models/category.py index c1c4cb3937c..f33e0254c1e 100644 --- a/samples/client/petstore/python/petstore_api/models/category.py +++ b/samples/client/petstore/python/petstore_api/models/category.py @@ -54,6 +54,7 @@ def __init__(self, id=None, name=None): self._id = id self._name = name + @property def id(self): """ diff --git a/samples/client/petstore/python/petstore_api/models/client.py b/samples/client/petstore/python/petstore_api/models/client.py new file mode 100644 index 00000000000..af00af6d607 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/client.py @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from pprint import pformat +from six import iteritems +import re + + +class Client(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, client=None): + """ + Client - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'client': 'str' + } + + self.attribute_map = { + 'client': 'client' + } + + self._client = client + + + @property + def client(self): + """ + Gets the client of this Client. + + + :return: The client of this Client. + :rtype: str + """ + return self._client + + @client.setter + def client(self, client): + """ + Sets the client of this Client. + + + :param client: The client of this Client. + :type: str + """ + + self._client = client + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py index 065be5b2e1e..36a1f1a3cb4 100644 --- a/samples/client/petstore/python/petstore_api/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -57,6 +57,7 @@ def __init__(self, class_name=None, color='red', breed=None): self._color = color self._breed = breed + @property def class_name(self): """ @@ -77,6 +78,8 @@ def class_name(self, class_name): :param class_name: The class_name of this Dog. :type: str """ + if class_name is None: + raise ValueError("Invalid value for `class_name`, must not be `None`") self._class_name = class_name diff --git a/samples/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/client/petstore/python/petstore_api/models/enum_arrays.py new file mode 100644 index 00000000000..5caaaa07497 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/enum_arrays.py @@ -0,0 +1,165 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from pprint import pformat +from six import iteritems +import re + + +class EnumArrays(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, just_symbol=None, array_enum=None): + """ + EnumArrays - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'just_symbol': 'str', + 'array_enum': 'list[str]' + } + + self.attribute_map = { + 'just_symbol': 'just_symbol', + 'array_enum': 'array_enum' + } + + self._just_symbol = just_symbol + self._array_enum = array_enum + + + @property + def just_symbol(self): + """ + Gets the just_symbol of this EnumArrays. + + + :return: The just_symbol of this EnumArrays. + :rtype: str + """ + return self._just_symbol + + @just_symbol.setter + def just_symbol(self, just_symbol): + """ + Sets the just_symbol of this EnumArrays. + + + :param just_symbol: The just_symbol of this EnumArrays. + :type: str + """ + allowed_values = [">=", "$"] + if just_symbol not in allowed_values: + raise ValueError( + "Invalid value for `just_symbol` ({0}), must be one of {1}" + .format(just_symbol, allowed_values) + ) + + self._just_symbol = just_symbol + + @property + def array_enum(self): + """ + Gets the array_enum of this EnumArrays. + + + :return: The array_enum of this EnumArrays. + :rtype: list[str] + """ + return self._array_enum + + @array_enum.setter + def array_enum(self, array_enum): + """ + Sets the array_enum of this EnumArrays. + + + :param array_enum: The array_enum of this EnumArrays. + :type: list[str] + """ + allowed_values = ["fish", "crab"] + 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))), + ", ".join(map(str, allowed_values))) + ) + + self._array_enum = array_enum + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/enum_class.py b/samples/client/petstore/python/petstore_api/models/enum_class.py index c15a1a25aad..930ec53b2ab 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python/petstore_api/models/enum_class.py @@ -49,6 +49,7 @@ def __init__(self): } + def to_dict(self): """ Returns the model properties as a dict 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 c498c839bd6..f405459389b 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -57,6 +57,7 @@ def __init__(self, enum_string=None, enum_integer=None, enum_number=None): self._enum_integer = enum_integer self._enum_number = enum_number + @property def enum_string(self): """ @@ -80,8 +81,8 @@ def enum_string(self, enum_string): allowed_values = ["UPPER", "lower"] if enum_string not in allowed_values: raise ValueError( - "Invalid value for `enum_string`, must be one of {0}" - .format(allowed_values) + "Invalid value for `enum_string` ({0}), must be one of {1}" + .format(enum_string, allowed_values) ) self._enum_string = enum_string @@ -109,8 +110,8 @@ def enum_integer(self, enum_integer): allowed_values = ["1", "-1"] if enum_integer not in allowed_values: raise ValueError( - "Invalid value for `enum_integer`, must be one of {0}" - .format(allowed_values) + "Invalid value for `enum_integer` ({0}), must be one of {1}" + .format(enum_integer, allowed_values) ) self._enum_integer = enum_integer @@ -138,8 +139,8 @@ def enum_number(self, enum_number): allowed_values = ["1.1", "-1.2"] if enum_number not in allowed_values: raise ValueError( - "Invalid value for `enum_number`, must be one of {0}" - .format(allowed_values) + "Invalid value for `enum_number` ({0}), must be one of {1}" + .format(enum_number, allowed_values) ) self._enum_number = enum_number 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 37b7e975f26..3c8682fdeca 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -87,6 +87,7 @@ def __init__(self, integer=None, int32=None, int64=None, number=None, float=None self._uuid = uuid self._password = password + @property def integer(self): """ @@ -107,12 +108,9 @@ def integer(self, integer): :param integer: The integer of this FormatTest. :type: int """ - - if not integer: - raise ValueError("Invalid value for `integer`, must not be `None`") - if integer > 100.0: + if integer is not None and integer > 100.0: raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") - if integer < 10.0: + if integer is not None and integer < 10.0: raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") self._integer = integer @@ -137,12 +135,9 @@ def int32(self, int32): :param int32: The int32 of this FormatTest. :type: int """ - - if not int32: - raise ValueError("Invalid value for `int32`, must not be `None`") - if int32 > 200.0: + if int32 is not None and int32 > 200.0: raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") - if int32 < 20.0: + if int32 is not None and int32 < 20.0: raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") self._int32 = int32 @@ -190,12 +185,11 @@ def number(self, number): :param number: The number of this FormatTest. :type: float """ - - if not number: + if number is None: raise ValueError("Invalid value for `number`, must not be `None`") - if number > 543.2: + 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 < 32.1: + 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`") self._number = number @@ -220,12 +214,9 @@ def float(self, float): :param float: The float of this FormatTest. :type: float """ - - if not float: - raise ValueError("Invalid value for `float`, must not be `None`") - if float > 987.6: + if float 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 < 54.3: + 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`") self._float = float @@ -250,12 +241,9 @@ def double(self, double): :param double: The double of this FormatTest. :type: float """ - - if not double: - raise ValueError("Invalid value for `double`, must not be `None`") - if double > 123.4: + if double 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 < 67.8: + 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`") self._double = double @@ -280,10 +268,7 @@ def string(self, string): :param string: The string of this FormatTest. :type: str """ - - if not string: - raise ValueError("Invalid value for `string`, must not be `None`") - if not re.search('[a-z]', string, flags=re.IGNORECASE): + if 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`") self._string = string @@ -308,6 +293,8 @@ def byte(self, byte): :param byte: The byte of this FormatTest. :type: str """ + if byte is None: + raise ValueError("Invalid value for `byte`, must not be `None`") self._byte = byte @@ -354,6 +341,8 @@ def date(self, date): :param date: The date of this FormatTest. :type: date """ + if date is None: + raise ValueError("Invalid value for `date`, must not be `None`") self._date = date @@ -423,12 +412,11 @@ def password(self, password): :param password: The password of this FormatTest. :type: str """ - - if not password: + if password is None: raise ValueError("Invalid value for `password`, must not be `None`") - if len(password) > 64: - raise ValueError("Invalid value for `password`, length must be less than `64`") - if len(password) < 10: + if password is not None and len(password) > 64: + raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") + if password is not None and len(password) < 10: raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") self._password = password 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 1a7943841b5..05dffbbfdac 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 @@ -32,7 +32,7 @@ class HasOnlyReadOnly(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, bar=None, foo=None): """ HasOnlyReadOnly - a model defined in Swagger @@ -51,8 +51,9 @@ def __init__(self): 'foo': 'foo' } - self._bar = None - self._foo = None + self._bar = bar + self._foo = foo + @property def bar(self): @@ -65,6 +66,18 @@ def bar(self): """ return self._bar + @bar.setter + def bar(self, bar): + """ + Sets the bar of this HasOnlyReadOnly. + + + :param bar: The bar of this HasOnlyReadOnly. + :type: str + """ + + self._bar = bar + @property def foo(self): """ @@ -76,6 +89,18 @@ def foo(self): """ return self._foo + @foo.setter + def foo(self, foo): + """ + Sets the foo of this HasOnlyReadOnly. + + + :param foo: The foo of this HasOnlyReadOnly. + :type: str + """ + + self._foo = foo + def to_dict(self): """ Returns the model properties as a dict diff --git a/samples/client/petstore/python/petstore_api/models/list.py b/samples/client/petstore/python/petstore_api/models/list.py new file mode 100644 index 00000000000..d51f73cc35c --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/list.py @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from pprint import pformat +from six import iteritems +import re + + +class List(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, _123_list=None): + """ + List - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + '_123_list': 'str' + } + + self.attribute_map = { + '_123_list': '123-list' + } + + self.__123_list = _123_list + + + @property + def _123_list(self): + """ + Gets the _123_list of this List. + + + :return: The _123_list of this List. + :rtype: str + """ + return self.__123_list + + @_123_list.setter + def _123_list(self, _123_list): + """ + Sets the _123_list of this List. + + + :param _123_list: The _123_list of this List. + :type: str + """ + + self.__123_list = _123_list + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index e48a39d49e6..9c4f9f5a931 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -32,7 +32,7 @@ class MapTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, map_map_of_string=None, map_map_of_enum=None, map_of_enum_string=None): + def __init__(self, map_map_of_string=None, map_of_enum_string=None): """ MapTest - a model defined in Swagger @@ -43,20 +43,18 @@ def __init__(self, map_map_of_string=None, map_map_of_enum=None, map_of_enum_str """ self.swagger_types = { 'map_map_of_string': 'dict(str, dict(str, str))', - 'map_map_of_enum': 'dict(str, dict(str, str))', 'map_of_enum_string': 'dict(str, str)' } self.attribute_map = { 'map_map_of_string': 'map_map_of_string', - 'map_map_of_enum': 'map_map_of_enum', 'map_of_enum_string': 'map_of_enum_string' } self._map_map_of_string = map_map_of_string - self._map_map_of_enum = map_map_of_enum self._map_of_enum_string = map_of_enum_string + @property def map_map_of_string(self): """ @@ -80,35 +78,6 @@ def map_map_of_string(self, map_map_of_string): self._map_map_of_string = map_map_of_string - @property - def map_map_of_enum(self): - """ - Gets the map_map_of_enum of this MapTest. - - - :return: The map_map_of_enum of this MapTest. - :rtype: dict(str, dict(str, str)) - """ - return self._map_map_of_enum - - @map_map_of_enum.setter - def map_map_of_enum(self, map_map_of_enum): - """ - Sets the map_map_of_enum of this MapTest. - - - :param map_map_of_enum: The map_map_of_enum of this MapTest. - :type: dict(str, dict(str, str)) - """ - allowed_values = [] - if map_map_of_enum not in allowed_values: - raise ValueError( - "Invalid value for `map_map_of_enum`, must be one of {0}" - .format(allowed_values) - ) - - self._map_map_of_enum = map_map_of_enum - @property def map_of_enum_string(self): """ @@ -129,11 +98,12 @@ def map_of_enum_string(self, map_of_enum_string): :param map_of_enum_string: The map_of_enum_string of this MapTest. :type: dict(str, str) """ - allowed_values = [] - if map_of_enum_string not in allowed_values: + allowed_values = ["UPPER", "lower"] + if not set(map_of_enum_string.keys()).issubset(set(allowed_values)): raise ValueError( - "Invalid value for `map_of_enum_string`, must be one of {0}" - .format(allowed_values) + "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))), + ", ".join(map(str, allowed_values))) ) self._map_of_enum_string = map_of_enum_string 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 94c94fe494c..b2e6f4714c3 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 @@ -57,6 +57,7 @@ def __init__(self, uuid=None, date_time=None, map=None): self._date_time = date_time self._map = map + @property def uuid(self): """ 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 9c323a85bfd..3793ec00174 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 @@ -54,6 +54,7 @@ def __init__(self, name=None, _class=None): self._name = name self.__class = _class + @property def name(self): """ 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 9dc6000526a..31369097694 100644 --- a/samples/client/petstore/python/petstore_api/models/model_return.py +++ b/samples/client/petstore/python/petstore_api/models/model_return.py @@ -51,6 +51,7 @@ def __init__(self, _return=None): self.__return = _return + @property def _return(self): """ diff --git a/samples/client/petstore/python/petstore_api/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py index df4eae8c765..a613643c624 100644 --- a/samples/client/petstore/python/petstore_api/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -32,7 +32,7 @@ class Name(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, name=None, _property=None): + def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): """ Name - a model defined in Swagger @@ -55,10 +55,11 @@ def __init__(self, name=None, _property=None): '_123_number': '123Number' } - self._snake_case = None - self.__123_number = None self._name = name + self._snake_case = snake_case self.__property = _property + self.__123_number = _123_number + @property def name(self): @@ -80,6 +81,8 @@ def name(self, name): :param name: The name of this Name. :type: int """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") self._name = name @@ -94,6 +97,18 @@ def snake_case(self): """ return self._snake_case + @snake_case.setter + def snake_case(self, snake_case): + """ + Sets the snake_case of this Name. + + + :param snake_case: The snake_case of this Name. + :type: int + """ + + self._snake_case = snake_case + @property def _property(self): """ @@ -128,6 +143,18 @@ def _123_number(self): """ return self.__123_number + @_123_number.setter + def _123_number(self, _123_number): + """ + Sets the _123_number of this Name. + + + :param _123_number: The _123_number of this Name. + :type: int + """ + + self.__123_number = _123_number + def to_dict(self): """ Returns the model properties as a dict 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 61ade0309e3..44928b2ea97 100644 --- a/samples/client/petstore/python/petstore_api/models/number_only.py +++ b/samples/client/petstore/python/petstore_api/models/number_only.py @@ -51,6 +51,7 @@ def __init__(self, just_number=None): self._just_number = just_number + @property def just_number(self): """ diff --git a/samples/client/petstore/python/petstore_api/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py index f3881a04405..9d2d2370e0c 100644 --- a/samples/client/petstore/python/petstore_api/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -66,6 +66,7 @@ def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=N self._status = status self._complete = complete + @property def id(self): """ @@ -181,8 +182,8 @@ def status(self, status): allowed_values = ["placed", "approved", "delivered"] if status not in allowed_values: raise ValueError( - "Invalid value for `status`, must be one of {0}" - .format(allowed_values) + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) ) self._status = status diff --git a/samples/client/petstore/python/petstore_api/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py index 7a86761e55f..93d3699cd0d 100644 --- a/samples/client/petstore/python/petstore_api/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -66,6 +66,7 @@ def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None self._tags = tags self._status = status + @property def id(self): """ @@ -132,6 +133,8 @@ def name(self, name): :param name: The name of this Pet. :type: str """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") self._name = name @@ -155,6 +158,8 @@ def photo_urls(self, photo_urls): :param photo_urls: The photo_urls of this Pet. :type: list[str] """ + if photo_urls is None: + raise ValueError("Invalid value for `photo_urls`, must not be `None`") self._photo_urls = photo_urls @@ -204,8 +209,8 @@ def status(self, status): allowed_values = ["available", "pending", "sold"] if status not in allowed_values: raise ValueError( - "Invalid value for `status`, must be one of {0}" - .format(allowed_values) + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) ) self._status = status 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 4dc49463a5c..c54d7aca5f6 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 @@ -32,7 +32,7 @@ class ReadOnlyFirst(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, baz=None): + def __init__(self, bar=None, baz=None): """ ReadOnlyFirst - a model defined in Swagger @@ -51,9 +51,10 @@ def __init__(self, baz=None): 'baz': 'baz' } - self._bar = None + self._bar = bar self._baz = baz + @property def bar(self): """ @@ -65,6 +66,18 @@ def bar(self): """ return self._bar + @bar.setter + def bar(self, bar): + """ + Sets the bar of this ReadOnlyFirst. + + + :param bar: The bar of this ReadOnlyFirst. + :type: str + """ + + self._bar = bar + @property def baz(self): """ 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 237f6d7ceeb..ca969d09df1 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 @@ -51,6 +51,7 @@ def __init__(self, special_property_name=None): self._special_property_name = special_property_name + @property def special_property_name(self): """ diff --git a/samples/client/petstore/python/petstore_api/models/tag.py b/samples/client/petstore/python/petstore_api/models/tag.py index cb5b0ea93ac..b898b80e401 100644 --- a/samples/client/petstore/python/petstore_api/models/tag.py +++ b/samples/client/petstore/python/petstore_api/models/tag.py @@ -54,6 +54,7 @@ def __init__(self, id=None, name=None): self._id = id self._name = name + @property def id(self): """ diff --git a/samples/client/petstore/python/petstore_api/models/user.py b/samples/client/petstore/python/petstore_api/models/user.py index 93dbd5884d8..2f504292ff8 100644 --- a/samples/client/petstore/python/petstore_api/models/user.py +++ b/samples/client/petstore/python/petstore_api/models/user.py @@ -72,6 +72,7 @@ def __init__(self, id=None, username=None, first_name=None, last_name=None, emai self._phone = phone self._user_status = user_status + @property def id(self): """ diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index c42861d0581..f8a4457ebae 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -24,15 +24,16 @@ from __future__ import absolute_import -import sys import io import json import ssl import certifi import logging +import re # python 2 and python 3 compatibility library -from six import iteritems +from six import PY3 +from six.moves.urllib.parse import urlencode from .configuration import Configuration @@ -41,13 +42,6 @@ except ImportError: raise ImportError('Swagger python client requires urllib3.') -try: - # for python3 - from urllib.parse import urlencode -except ImportError: - # for python2 - from urllib import urlencode - logger = logging.getLogger(__name__) @@ -119,7 +113,7 @@ def request(self, method, url, query_params=None, headers=None, :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, - `application/x-www-form-urlencode` + `application/x-www-form-urlencoded` and `multipart/form-data` """ method = method.upper() @@ -141,19 +135,19 @@ def request(self, method, url, query_params=None, headers=None, if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': + if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) r = self.pool_manager.request(method, url, body=request_body, headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, headers=headers) - if headers['Content-Type'] == 'multipart/form-data': + elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type # which generated by urllib3 will be overwritten. del headers['Content-Type'] @@ -161,6 +155,19 @@ def request(self, method, url, query_params=None, headers=None, fields=post_params, encode_multipart=True, 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 + elif isinstance(body, str): + request_body = body + r = self.pool_manager.request(method, url, + body=request_body, + 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.""" + raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, @@ -174,11 +181,11 @@ def request(self, method, url, query_params=None, headers=None, # In the python 3, the response.data is bytes. # we need to decode it to string. - if sys.version_info > (3,): + if PY3: r.data = r.data.decode('utf8') # log response body - logger.debug("response body: %s" % r.data) + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) diff --git a/samples/client/petstore/python/test/test_client.py b/samples/client/petstore/python/test/test_client.py new file mode 100644 index 00000000000..fe52aafed9b --- /dev/null +++ b/samples/client/petstore/python/test/test_client.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.client import Client + + +class TestClient(unittest.TestCase): + """ Client unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testClient(self): + """ + Test Client + """ + model = petstore_api.models.client.Client() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_enum_arrays.py b/samples/client/petstore/python/test/test_enum_arrays.py new file mode 100644 index 00000000000..ba9c899530b --- /dev/null +++ b/samples/client/petstore/python/test/test_enum_arrays.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.enum_arrays import EnumArrays + + +class TestEnumArrays(unittest.TestCase): + """ EnumArrays unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testEnumArrays(self): + """ + Test EnumArrays + """ + model = petstore_api.models.enum_arrays.EnumArrays() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_list.py b/samples/client/petstore/python/test/test_list.py new file mode 100644 index 00000000000..5558d752cd0 --- /dev/null +++ b/samples/client/petstore/python/test/test_list.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.list import List + + +class TestList(unittest.TestCase): + """ List unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testList(self): + """ + Test List + """ + model = petstore_api.models.list.List() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test_python2.sh b/samples/client/petstore/python/test_python2.sh index 680d2ce61e0..e2492be49f6 100755 --- a/samples/client/petstore/python/test_python2.sh +++ b/samples/client/petstore/python/test_python2.sh @@ -6,6 +6,9 @@ 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 diff --git a/samples/client/petstore/python/test_python2_and_3.sh b/samples/client/petstore/python/test_python2_and_3.sh index 2e4b4630a33..b917ecad06a 100755 --- a/samples/client/petstore/python/test_python2_and_3.sh +++ b/samples/client/petstore/python/test_python2_and_3.sh @@ -6,6 +6,9 @@ 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 diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py index 8df2b681f01..d1f9dbaa6f2 100644 --- a/samples/client/petstore/python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -9,12 +9,12 @@ import os import sys -import time import unittest import petstore_api from petstore_api.rest import ApiException +from .util import id_gen class ApiExceptionTests(unittest.TestCase): @@ -25,22 +25,19 @@ def setUp(self): def setUpModels(self): self.category = petstore_api.Category() - self.category.id = int(time.time()) + self.category.id = id_gen() self.category.name = "dog" self.tag = petstore_api.Tag() - self.tag.id = int(time.time()) + self.tag.id = id_gen() self.tag.name = "blank" self.pet = petstore_api.Pet() - self.pet.id = int(time.time()) + self.pet.id = id_gen() self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] self.pet.status = "sold" self.pet.category = self.category self.pet.tags = [self.tag] - def tearDown(self): - time.sleep(1) - def test_404_error(self): self.pet_api.add_pet(body=self.pet) self.pet_api.delete_pet(pet_id=self.pet.id) diff --git a/samples/client/petstore/python/tests/test_enum_arrays.py b/samples/client/petstore/python/tests/test_enum_arrays.py new file mode 100644 index 00000000000..aa373339a60 --- /dev/null +++ b/samples/client/petstore/python/tests/test_enum_arrays.py @@ -0,0 +1,164 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" + +import os +import time +import unittest + +import petstore_api + + +class EnumArraysTests(unittest.TestCase): + + def test_enumarrays_init(self): + # + # Check various combinations of valid values. + # + fish_or_crab = petstore_api.EnumArrays(just_symbol=">=") + self.assertEqual(fish_or_crab.just_symbol, ">=") + self.assertEqual(fish_or_crab.array_enum, None) + + fish_or_crab = petstore_api.EnumArrays(just_symbol="$", array_enum=["fish"]) + self.assertEqual(fish_or_crab.just_symbol, "$") + self.assertEqual(fish_or_crab.array_enum, ["fish"]) + + fish_or_crab = petstore_api.EnumArrays(just_symbol=">=", array_enum=["fish"]) + self.assertEqual(fish_or_crab.just_symbol, ">=") + self.assertEqual(fish_or_crab.array_enum, ["fish"]) + + fish_or_crab = petstore_api.EnumArrays("$", ["crab"]) + self.assertEqual(fish_or_crab.just_symbol, "$") + self.assertEqual(fish_or_crab.array_enum, ["crab"]) + + + # + # Check if setting invalid values fails + # + try: + fish_or_crab = petstore_api.EnumArrays(just_symbol="<=") + except ValueError: + self.assertEqual(fish_or_crab.just_symbol, None) + self.assertEqual(fish_or_crab.array_enum, None) + + try: + fish_or_crab = petstore_api.EnumArrays(just_symbol="$", array_enum=["dog"]) + except ValueError: + self.assertEqual(fish_or_crab.just_symbol, None) + self.assertEqual(fish_or_crab.array_enum, None) + + + try: + fish_or_crab = petstore_api.EnumArrays(just_symbol=["$"], array_enum=["dog"]) + except ValueError: + self.assertEqual(fish_or_crab.just_symbol, None) + self.assertEqual(fish_or_crab.array_enum, None) + + + def test_enumarrays_setter(self): + + # + # Check various combinations of valid values + # + fish_or_crab = petstore_api.EnumArrays() + + fish_or_crab.just_symbol = ">=" + self.assertEqual(fish_or_crab.just_symbol, ">=") + + fish_or_crab.just_symbol = "$" + self.assertEqual(fish_or_crab.just_symbol, "$") + + fish_or_crab.array_enum = [] + self.assertEqual(fish_or_crab.array_enum, []) + + fish_or_crab.array_enum = ["fish"] + self.assertEqual(fish_or_crab.array_enum, ["fish"]) + + fish_or_crab.array_enum = ["fish", "fish", "fish"] + self.assertEqual(fish_or_crab.array_enum, ["fish", "fish", "fish"]) + + fish_or_crab.array_enum = ["crab"] + self.assertEqual(fish_or_crab.array_enum, ["crab"]) + + fish_or_crab.array_enum = ["crab", "fish"] + self.assertEqual(fish_or_crab.array_enum, ["crab", "fish"]) + + fish_or_crab.array_enum = ["crab", "fish", "crab", "fish"] + self.assertEqual(fish_or_crab.array_enum, ["crab", "fish", "crab", "fish"]) + + # + # Check if setting invalid values fails + # + fish_or_crab = petstore_api.EnumArrays() + try: + fish_or_crab.just_symbol = "!=" + except ValueError: + self.assertEqual(fish_or_crab.just_symbol, None) + + try: + fish_or_crab.just_symbol = ["fish"] + except ValueError: + self.assertEqual(fish_or_crab.just_symbol, None) + + try: + fish_or_crab.array_enum = ["cat"] + except ValueError: + self.assertEqual(fish_or_crab.array_enum, None) + + try: + fish_or_crab.array_enum = ["fish", "crab", "dog"] + except ValueError: + self.assertEqual(fish_or_crab.array_enum, None) + + try: + fish_or_crab.array_enum = "fish" + except ValueError: + self.assertEqual(fish_or_crab.array_enum, None) + + + def test_todict(self): + # + # Check if dictionary serialization works + # + dollar_fish_crab_dict = { + 'just_symbol': "$", + 'array_enum': ["fish", "crab"] + } + + dollar_fish_crab = petstore_api.EnumArrays("$", ["fish", "crab"]) + + self.assertEqual(dollar_fish_crab_dict, dollar_fish_crab.to_dict()) + + # + # Sanity check for different arrays + # + dollar_crab_fish_dict = { + 'just_symbol': "$", + 'array_enum': ["crab", "fish"] + } + + dollar_fish_crab = petstore_api.EnumArrays("$", ["fish", "crab"]) + + self.assertNotEqual(dollar_crab_fish_dict, dollar_fish_crab.to_dict()) + + + def test_equals(self): + # + # Check if object comparison works + # + fish1 = petstore_api.EnumArrays("$", ["fish"]) + fish2 = petstore_api.EnumArrays("$", ["fish"]) + self.assertEqual(fish1, fish2) + + fish = petstore_api.EnumArrays("$", ["fish"]) + crab = petstore_api.EnumArrays("$", ["crab"]) + self.assertNotEqual(fish, crab) + + dollar = petstore_api.EnumArrays("$") + greater = petstore_api.EnumArrays(">=") + self.assertNotEqual(dollar, greater) \ No newline at end of file diff --git a/samples/client/petstore/python/tests/test_map_test.py b/samples/client/petstore/python/tests/test_map_test.py new file mode 100644 index 00000000000..3ed54f93d24 --- /dev/null +++ b/samples/client/petstore/python/tests/test_map_test.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" + +import os +import time +import unittest + +import petstore_api + + +class MapTestTests(unittest.TestCase): + + + def test_maptest_init(self): + # + # Test MapTest construction with valid values + # + up_or_low_dict = { + 'UPPER': "UP", + 'lower': "low" + } + map_enum_test = petstore_api.MapTest(map_of_enum_string=up_or_low_dict) + + self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict) + + map_of_map_of_strings = { + 'val1': 1, + 'valText': "Text", + 'valueDict': up_or_low_dict + } + map_enum_test = petstore_api.MapTest(map_map_of_string=map_of_map_of_strings) + + self.assertEqual(map_enum_test.map_map_of_string, map_of_map_of_strings) + + # + # Make sure that the init fails for invalid enum values + # + black_or_white_dict = { + 'black': "UP", + 'white': "low" + } + try: + map_enum_test = petstore_api.MapTest(map_of_enum_string=black_or_white_dict) + except ValueError: + self.assertEqual(map_enum_test, None) + + + def test_maptest_setter(self): + # + # Check with some valid values + # + map_enum_test = petstore_api.MapTest() + up_or_low_dict = { + 'UPPER': "UP", + 'lower': "low" + } + map_enum_test.map_of_enum_string = up_or_low_dict + self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict) + + + # + # Check if the setter fails for invalid enum values + # + map_enum_test = petstore_api.MapTest() + black_or_white_dict = { + 'black': "UP", + 'white': "low" + } + try: + map_enum_test.map_of_enum_string = black_or_white_dict + except ValueError: + self.assertEqual(map_enum_test.map_of_enum_string, None) + + + def test_todict(self): + # + # Check dictionary serialization + # + map_enum_test = petstore_api.MapTest() + up_or_low_dict = { + 'UPPER': "UP", + 'lower': "low" + } + map_of_map_of_strings = { + 'val1': 1, + 'valText': "Text", + 'valueDict': up_or_low_dict + } + map_enum_test.map_of_enum_string = up_or_low_dict + map_enum_test.map_map_of_string = map_of_map_of_strings + + self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict) + self.assertEqual(map_enum_test.map_map_of_string, map_of_map_of_strings) + + expected_dict = { + 'map_of_enum_string': up_or_low_dict, + 'map_map_of_string': map_of_map_of_strings + } + + self.assertEqual(map_enum_test.to_dict(), expected_dict) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 37fe5a55212..33c6d86c14a 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -8,14 +8,14 @@ """ import os -import time import unittest import petstore_api from petstore_api.rest import ApiException -HOST = 'http://petstore.swagger.io/v2' +from .util import id_gen +HOST = 'http://petstore.swagger.io/v2' class PetApiTests(unittest.TestCase): @@ -25,19 +25,15 @@ def setUp(self): self.setUpModels() self.setUpFiles() - def tearDown(self): - # sleep 1 sec between two every 2 tests - time.sleep(1) - def setUpModels(self): self.category = petstore_api.Category() - self.category.id = int(time.time()) + self.category.id = id_gen() self.category.name = "dog" self.tag = petstore_api.Tag() - self.tag.id = int(time.time()) + self.tag.id = id_gen() self.tag.name = "swagger-codegen-python-pet-tag" self.pet = petstore_api.Pet() - self.pet.id = int(time.time()) + self.pet.id = id_gen() self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] self.pet.status = "sold" @@ -155,6 +151,7 @@ def test_find_pets_by_status(self): list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status]))) ) + @unittest.skip("skipping the test as the method sometimes invalid Petstore object with incorrect status") def test_find_pets_by_tags(self): self.pet_api.add_pet(body=self.pet) @@ -199,7 +196,7 @@ def test_delete_pet(self): try: self.pet_api.get_pet_by_id(pet_id=self.pet.id) - raise "expected an error" + raise Exception("expected an error") except ApiException as e: self.assertEqual(404, e.status) diff --git a/samples/client/petstore/python/tests/util.py b/samples/client/petstore/python/tests/util.py new file mode 100644 index 00000000000..6aeea16f63e --- /dev/null +++ b/samples/client/petstore/python/tests/util.py @@ -0,0 +1,5 @@ +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/ruby/.swagger-codegen-ignore b/samples/client/petstore/ruby/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/ruby/.swagger-codegen-ignore +++ b/samples/client/petstore/ruby/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 440aca6ef62..188335045f6 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-29T13:19:03.533-07:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -57,15 +56,15 @@ require 'petstore' api_instance = Petstore::FakeApi.new -opts = { - test_code_inject__end: "test_code_inject__end_example" # String | To test code injection */ -} +body = Petstore::Client.new # Client | client model + begin - #To test code injection */ - api_instance.test_code_inject__end(opts) + #To test \"client\" model + result = api_instance.test_client_model(body) + p result rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->test_code_inject__end: #{e}" + puts "Exception when calling FakeApi->test_client_model: #{e}" end ``` @@ -76,9 +75,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*Petstore::FakeApi* | [**test_code_inject__end**](docs/FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ +*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_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +*Petstore::FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters *Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -112,11 +111,14 @@ Class | Method | HTTP request | Description - [Petstore::ArrayTest](docs/ArrayTest.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) + - [Petstore::Client](docs/Client.md) - [Petstore::Dog](docs/Dog.md) + - [Petstore::EnumArrays](docs/EnumArrays.md) - [Petstore::EnumClass](docs/EnumClass.md) - [Petstore::EnumTest](docs/EnumTest.md) - [Petstore::FormatTest](docs/FormatTest.md) - [Petstore::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Petstore::List](docs/List.md) - [Petstore::MapTest](docs/MapTest.md) - [Petstore::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Petstore::Model200Response](docs/Model200Response.md) @@ -134,6 +136,16 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth @@ -143,9 +155,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/ruby/docs/Client.md b/samples/client/petstore/ruby/docs/Client.md new file mode 100644 index 00000000000..2b8e400aaee --- /dev/null +++ b/samples/client/petstore/ruby/docs/Client.md @@ -0,0 +1,8 @@ +# Petstore::Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/EnumArrays.md b/samples/client/petstore/ruby/docs/EnumArrays.md new file mode 100644 index 00000000000..ef6a935fbd7 --- /dev/null +++ b/samples/client/petstore/ruby/docs/EnumArrays.md @@ -0,0 +1,9 @@ +# Petstore::EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **String** | | [optional] +**array_enum** | **Array<String>** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 94e1ab7f200..1524d9c915f 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject__end**](FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ +[**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_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -# **test_code_inject__end** -> test_code_inject__end(opts) +# **test_client_model** +> Client test_client_model(body) -To test code injection */ +To test \"client\" model ### Example ```ruby @@ -21,15 +21,15 @@ require 'petstore' api_instance = Petstore::FakeApi.new -opts = { - test_code_inject__end: "test_code_inject__end_example" # String | To test code injection */ -} +body = Petstore::Client.new # Client | client model + begin - #To test code injection */ - api_instance.test_code_inject__end(opts) + #To test \"client\" model + result = api_instance.test_client_model(body) + p result rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->test_code_inject__end: #{e}" + puts "Exception when calling FakeApi->test_client_model: #{e}" end ``` @@ -37,11 +37,11 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test_code_inject__end** | **String**| To test code injection */ | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -nil (empty response body) +[**Client**](Client.md) ### Authorization @@ -49,13 +49,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json # **test_endpoint_parameters** -> test_endpoint_parameters(number, double, string, byte, opts) +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -65,6 +65,12 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ```ruby # load the gem require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure HTTP basic authorization: http_basic_test + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD' +end api_instance = Petstore::FakeApi.new @@ -72,7 +78,7 @@ number = 3.4 # Float | None double = 1.2 # Float | None -string = "string_example" # String | None +pattern_without_delimiter = "pattern_without_delimiter_example" # String | None byte = "B" # String | None @@ -81,15 +87,17 @@ opts = { int32: 56, # Integer | None int64: 789, # Integer | None float: 3.4, # Float | None + string: "string_example", # String | None binary: "B", # String | None date: Date.parse("2013-10-20"), # Date | None date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None - password: "password_example" # String | None + password: "password_example", # String | None + callback: "callback_example" # String | None } begin #Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, string, byte, opts) + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" end @@ -101,16 +109,18 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **Float**| None | **double** | **Float**| None | - **string** | **String**| None | + **pattern_without_delimiter** | **String**| None | **byte** | **String**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Integer**| None | [optional] **float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **String**| None | [optional] **date** | **Date**| None | [optional] **date_time** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **callback** | **String**| None | [optional] ### Return type @@ -118,7 +128,7 @@ nil (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -127,10 +137,10 @@ No authorization required -# **test_enum_query_parameters** -> test_enum_query_parameters(opts) +# **test_enum_parameters** +> test_enum_parameters(opts) -To test enum query parameters +To test enum parameters ### Example ```ruby @@ -140,16 +150,21 @@ require 'petstore' api_instance = Petstore::FakeApi.new opts = { + enum_form_string_array: ["enum_form_string_array_example"], # Array | Form parameter enum test (string array) + enum_form_string: "-efg", # String | Form parameter enum test (string) + enum_header_string_array: ["enum_header_string_array_example"], # Array | Header parameter enum test (string array) + enum_header_string: "-efg", # String | Header parameter enum test (string) + enum_query_string_array: ["enum_query_string_array_example"], # Array | Query parameter enum test (string array) enum_query_string: "-efg", # String | Query parameter enum test (string) enum_query_integer: 3.4, # Float | Query parameter enum test (double) enum_query_double: 1.2 # Float | Query parameter enum test (double) } begin - #To test enum query parameters - api_instance.test_enum_query_parameters(opts) + #To test enum parameters + api_instance.test_enum_parameters(opts) rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->test_enum_query_parameters: #{e}" + puts "Exception when calling FakeApi->test_enum_parameters: #{e}" end ``` @@ -157,6 +172,11 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**Array<String>**](String.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **String**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**Array<String>**](String.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **String**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**Array<String>**](String.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **String**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **Float**| Query parameter enum test (double) | [optional] **enum_query_double** | **Float**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/ruby/docs/List.md b/samples/client/petstore/ruby/docs/List.md new file mode 100644 index 00000000000..211d299f671 --- /dev/null +++ b/samples/client/petstore/ruby/docs/List.md @@ -0,0 +1,8 @@ +# Petstore::List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/MapTest.md b/samples/client/petstore/ruby/docs/MapTest.md index e0ed8529bf8..902f1fbc511 100644 --- a/samples/client/petstore/ruby/docs/MapTest.md +++ b/samples/client/petstore/ruby/docs/MapTest.md @@ -4,7 +4,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_map_of_string** | **Hash<String, Hash<String, String>>** | | [optional] -**map_map_of_enum** | **Hash<String, Hash<String, String>>** | | [optional] **map_of_enum_string** | **Hash<String, String>** | | [optional] diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 407491a910a..9e296560fe5 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -37,11 +37,14 @@ require 'petstore/models/array_test' require 'petstore/models/cat' require 'petstore/models/category' +require 'petstore/models/client' require 'petstore/models/dog' +require 'petstore/models/enum_arrays' require 'petstore/models/enum_class' require 'petstore/models/enum_test' require 'petstore/models/format_test' require 'petstore/models/has_only_read_only' +require 'petstore/models/list' require 'petstore/models/map_test' require 'petstore/models/mixed_properties_and_additional_properties_class' require 'petstore/models/model_200_response' 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 39db2151ed7..0eaba370798 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -31,25 +31,27 @@ def initialize(api_client = ApiClient.default) @api_client = api_client end - # To test code injection */ + # To test \"client\" model # + # @param body client model # @param [Hash] opts the optional parameters - # @option opts [String] :test_code_inject__end To test code injection */ - # @return [nil] - def test_code_inject__end(opts = {}) - test_code_inject__end_with_http_info(opts) - return nil + # @return [Client] + def test_client_model(body, opts = {}) + data, _status_code, _headers = test_client_model_with_http_info(body, opts) + return data end - # To test code injection */ + # To test \"client\" model # + # @param body client model # @param [Hash] opts the optional parameters - # @option opts [String] :test_code_inject__end To test code injection */ - # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_code_inject__end_with_http_info(opts = {}) + # @return [Array<(Client, Fixnum, Hash)>] Client data, response status code and response headers + def test_client_model_with_http_info(body, opts = {}) if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: FakeApi.test_code_inject__end ..." + @api_client.config.logger.debug "Calling API: FakeApi.test_client_model ..." end + # verify the required parameter 'body' is set + fail ArgumentError, "Missing the required parameter 'body' when calling FakeApi.test_client_model" if body.nil? # resource path local_var_path = "/fake".sub('{format}','json') @@ -60,28 +62,28 @@ def test_code_inject__end_with_http_info(opts = {}) header_params = {} # HTTP header 'Accept' (if needed) - local_header_accept = ['application/json', '*/ end'] + local_header_accept = ['application/json'] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - local_header_content_type = ['application/json', '*/ =end));(phpinfo('] + local_header_content_type = ['application/json'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} - form_params["test code inject */ =end"] = opts[:'test_code_inject__end'] if !opts[:'test_code_inject__end'].nil? # http body (model) - post_body = nil + post_body = @api_client.object_to_http_body(body) auth_names = [] - data, status_code, headers = @api_client.call_api(:PUT, local_var_path, + 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) + :auth_names => auth_names, + :return_type => 'Client') if @api_client.config.debugging - @api_client.config.logger.debug "API called: FakeApi#test_code_inject__end\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + @api_client.config.logger.debug "API called: FakeApi#test_client_model\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -90,20 +92,22 @@ def test_code_inject__end_with_http_info(opts = {}) # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None - # @param string None + # @param pattern_without_delimiter None # @param byte None # @param [Hash] opts the optional parameters # @option opts [Integer] :integer None # @option opts [Integer] :int32 None # @option opts [Integer] :int64 None # @option opts [Float] :float None + # @option opts [String] :string None # @option opts [String] :binary None # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None + # @option opts [String] :callback None # @return [nil] - def test_endpoint_parameters(number, double, string, byte, opts = {}) - test_endpoint_parameters_with_http_info(number, double, string, byte, opts) + def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts = {}) + test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts) return nil end @@ -111,19 +115,21 @@ def test_endpoint_parameters(number, double, string, byte, opts = {}) # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None - # @param string None + # @param pattern_without_delimiter None # @param byte None # @param [Hash] opts the optional parameters # @option opts [Integer] :integer None # @option opts [Integer] :int32 None # @option opts [Integer] :int64 None # @option opts [Float] :float None + # @option opts [String] :string None # @option opts [String] :binary None # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None + # @option opts [String] :callback None # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = {}) + def test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: FakeApi.test_endpoint_parameters ..." end @@ -147,39 +153,43 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = fail ArgumentError, 'invalid value for "double" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 67.8.' end - # verify the required parameter 'string' is set - fail ArgumentError, "Missing the required parameter 'string' when calling FakeApi.test_endpoint_parameters" if string.nil? - if string !~ Regexp.new(/[a-z]/i) - fail ArgumentError, 'invalid value for "string" when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i.' + # verify the required parameter 'pattern_without_delimiter' is set + fail ArgumentError, "Missing the required parameter 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters" if pattern_without_delimiter.nil? + if pattern_without_delimiter !~ Regexp.new(/^[A-Z].*/) + fail ArgumentError, "invalid value for 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters, must conform to the pattern /^[A-Z].*/." end # verify the required parameter 'byte' is set fail ArgumentError, "Missing the required parameter 'byte' when calling FakeApi.test_endpoint_parameters" if byte.nil? - if opts[:'integer'] > 100.0 + if !opts[:'integer'].nil? && opts[:'integer'] > 100.0 fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.0.' end - if opts[:'integer'] < 10.0 + if !opts[:'integer'].nil? && opts[:'integer'] < 10.0 fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.0.' end - if opts[:'int32'] > 200.0 + if !opts[:'int32'].nil? && opts[:'int32'] > 200.0 fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.0.' end - if opts[:'int32'] < 20.0 + if !opts[:'int32'].nil? && opts[:'int32'] < 20.0 fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.0.' end - if opts[:'float'] > 987.6 + if !opts[:'float'].nil? && opts[:'float'] > 987.6 fail ArgumentError, 'invalid value for "opts[:"float"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 987.6.' end - if opts[:'password'].to_s.length > 64 + if !opts[:'string'].nil? && opts[:'string'] !~ Regexp.new(/[a-z]/i) + fail ArgumentError, "invalid value for 'opts[:\"string\"]' when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i." + end + + if !opts[:'password'].nil? && opts[:'password'].to_s.length > 64 fail ArgumentError, 'invalid value for "opts[:"password"]" when calling FakeApi.test_endpoint_parameters, the character length must be smaller than or equal to 64.' end - if opts[:'password'].to_s.length < 10 + if !opts[:'password'].nil? && opts[:'password'].to_s.length < 10 fail ArgumentError, 'invalid value for "opts[:"password"]" when calling FakeApi.test_endpoint_parameters, the character length must be great than or equal to 10.' end @@ -204,20 +214,22 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = form_params = {} form_params["number"] = number form_params["double"] = double - form_params["string"] = string + form_params["pattern_without_delimiter"] = pattern_without_delimiter form_params["byte"] = byte form_params["integer"] = opts[:'integer'] if !opts[:'integer'].nil? form_params["int32"] = opts[:'int32'] if !opts[:'int32'].nil? form_params["int64"] = opts[:'int64'] if !opts[:'int64'].nil? form_params["float"] = opts[:'float'] if !opts[:'float'].nil? + form_params["string"] = opts[:'string'] if !opts[:'string'].nil? form_params["binary"] = opts[:'binary'] if !opts[:'binary'].nil? form_params["date"] = opts[:'date'] if !opts[:'date'].nil? form_params["dateTime"] = opts[:'date_time'] if !opts[:'date_time'].nil? form_params["password"] = opts[:'password'] if !opts[:'password'].nil? + form_params["callback"] = opts[:'callback'] if !opts[:'callback'].nil? # http body (model) post_body = nil - auth_names = [] + auth_names = ['http_basic_test'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, @@ -230,28 +242,53 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = return data, status_code, headers end - # To test enum query parameters + # To test enum parameters # # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) (default to -efg) + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) (default to -efg) + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) (default to -efg) # @option opts [Float] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) # @return [nil] - def test_enum_query_parameters(opts = {}) - test_enum_query_parameters_with_http_info(opts) + def test_enum_parameters(opts = {}) + test_enum_parameters_with_http_info(opts) return nil end - # To test enum query parameters + # To test enum parameters # # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) # @option opts [Float] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_enum_query_parameters_with_http_info(opts = {}) + def test_enum_parameters_with_http_info(opts = {}) if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: FakeApi.test_enum_query_parameters ..." + @api_client.config.logger.debug "Calling API: FakeApi.test_enum_parameters ..." + end + if opts[:'enum_form_string_array'] && !['>', '$'].include?(opts[:'enum_form_string_array']) + fail ArgumentError, 'invalid value for "enum_form_string_array", must be one of >, $' + end + if opts[:'enum_form_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_form_string']) + fail ArgumentError, 'invalid value for "enum_form_string", must be one of _abc, -efg, (xyz)' + end + if opts[:'enum_header_string_array'] && !['>', '$'].include?(opts[:'enum_header_string_array']) + fail ArgumentError, 'invalid value for "enum_header_string_array", must be one of >, $' + end + if opts[:'enum_header_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_header_string']) + fail ArgumentError, 'invalid value for "enum_header_string", must be one of _abc, -efg, (xyz)' + end + if opts[:'enum_query_string_array'] && !['>', '$'].include?(opts[:'enum_query_string_array']) + fail ArgumentError, 'invalid value for "enum_query_string_array", must be one of >, $' end if opts[:'enum_query_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_query_string']) fail ArgumentError, 'invalid value for "enum_query_string", must be one of _abc, -efg, (xyz)' @@ -261,6 +298,8 @@ def test_enum_query_parameters_with_http_info(opts = {}) # query parameters query_params = {} + query_params[:'enum_query_string_array'] = @api_client.build_collection_param(opts[:'enum_query_string_array'], :csv) if !opts[:'enum_query_string_array'].nil? + query_params[:'enum_query_string'] = opts[:'enum_query_string'] if !opts[:'enum_query_string'].nil? query_params[:'enum_query_integer'] = opts[:'enum_query_integer'] if !opts[:'enum_query_integer'].nil? # header parameters @@ -273,10 +312,13 @@ def test_enum_query_parameters_with_http_info(opts = {}) # HTTP header 'Content-Type' local_header_content_type = ['application/json'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params[:'enum_header_string_array'] = @api_client.build_collection_param(opts[:'enum_header_string_array'], :csv) if !opts[:'enum_header_string_array'].nil? + header_params[:'enum_header_string'] = opts[:'enum_header_string'] if !opts[:'enum_header_string'].nil? # form parameters form_params = {} - form_params["enum_query_string"] = opts[:'enum_query_string'] if !opts[:'enum_query_string'].nil? + form_params["enum_form_string_array"] = @api_client.build_collection_param(opts[:'enum_form_string_array'], :csv) if !opts[:'enum_form_string_array'].nil? + form_params["enum_form_string"] = opts[:'enum_form_string'] if !opts[:'enum_form_string'].nil? form_params["enum_query_double"] = opts[:'enum_query_double'] if !opts[:'enum_query_double'].nil? # http body (model) @@ -289,7 +331,7 @@ def test_enum_query_parameters_with_http_info(opts = {}) :body => post_body, :auth_names => auth_names) if @api_client.config.debugging - @api_client.config.logger.debug "API called: FakeApi#test_enum_query_parameters\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + @api_client.config.logger.debug "API called: FakeApi#test_enum_parameters\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 66a0204e318..0a95711ce43 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -39,7 +39,7 @@ class ApiClient attr_accessor :default_headers # Initializes the ApiClient - # @option config [Configuration] Configuraiton for initializing the object, default to Configuration.default + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default def initialize(config = Configuration.default) @config = config @user_agent = "Swagger-Codegen/#{VERSION}/ruby" @@ -66,10 +66,18 @@ def call_api(http_method, path, opts = {}) end unless response.success? - fail ApiError.new(:code => response.code, - :response_headers => response.headers, - :response_body => response.body), - response.status_message + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end end if opts[:return_type] @@ -99,6 +107,9 @@ def build_request(http_method, path, opts = {}) update_params_for_auth! header_params, query_params, opts[:auth_names] + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + req_opts = { :method => http_method, :headers => header_params, @@ -106,11 +117,13 @@ def build_request(http_method, path, opts = {}) :params_encoding => @config.params_encoding, :timeout => @config.timeout, :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, :sslcert => @config.cert_file, :sslkey => @config.key_file, :verbose => @config.debugging } + # set custom cert, if provided req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert if [:post, :patch, :put, :delete].include?(http_method) @@ -130,7 +143,7 @@ def build_request(http_method, path, opts = {}) # application/json; charset=UTF8 # APPLICATION/JSON # @param [String] mime MIME - # @return [Boolean] True if the MIME is applicaton/json + # @return [Boolean] True if the MIME is application/json def json_mime?(mime) !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end @@ -216,7 +229,7 @@ def convert_to_type(data, return_type) # @return [Tempfile] the file downloaded def download_file(response) content_disposition = response.headers['Content-Disposition'] - if content_disposition + if content_disposition and content_disposition =~ /filename=/i filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] prefix = sanitize_filename(filename) else @@ -283,7 +296,7 @@ def build_request_body(header_params, form_params, body) # Update hearder and query params based on authentication settings. # # @param [Hash] header_params Header parameters - # @param [Hash] form_params Query parameters + # @param [Hash] query_params Query parameters # @param [String] auth_names Authentication scheme name def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index d132b0da37d..64166258b47 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -87,7 +87,7 @@ class Configuration # Default to 0 (never times out). attr_accessor :timeout - ### TLS/SSL + ### TLS/SSL setting # Set this to false to skip verifying SSL certificate when calling API from https server. # Default to true. # @@ -96,13 +96,16 @@ class Configuration # @return [true, false] attr_accessor :verify_ssl - # Set this to customize parameters encoding of array parameter with multi collectionFormat. - # Default to nil. + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. # - # @see The params_encoding option of Ethon. Related source code: - # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 - attr_accessor :params_encoding + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + ### TLS/SSL setting # Set this to customize the certificate file to verify the peer. # # @return [String] the path to the certificate file @@ -111,12 +114,21 @@ class Configuration # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 attr_accessor :ssl_ca_cert + ### TLS/SSL setting # Client certificate file (for client certificate) attr_accessor :cert_file + ### TLS/SSL setting # Client private key file (for client certificate) attr_accessor :key_file + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + attr_accessor :inject_format attr_accessor :force_ending_format @@ -129,6 +141,7 @@ def initialize @api_key_prefix = {} @timeout = 0 @verify_ssl = true + @verify_ssl_host = true @params_encoding = nil @cert_file = nil @key_file = nil @@ -188,13 +201,6 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { - 'petstore_auth' => - { - type: 'oauth2', - in: 'header', - key: 'Authorization', - value: "Bearer #{access_token}" - }, 'api_key' => { type: 'api_key', @@ -202,6 +208,20 @@ def auth_settings key: 'api_key', value: api_key_with_prefix('api_key') }, + 'http_basic_test' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, + 'petstore_auth' => + { + type: 'oauth2', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token}" + }, } end end 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 27bb91fea38..46829be071e 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 @@ -109,7 +109,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -140,7 +140,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -151,7 +151,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 692c736e98e..0e941aa2657 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -71,6 +71,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push("invalid value for 'class_name', class_name cannot be nil.") + end + return invalid_properties end @@ -108,7 +112,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -139,7 +143,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -150,7 +154,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb index 71a87330302..65b57cca515 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -87,7 +87,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -118,7 +118,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -129,7 +129,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index e8c413b5b4f..21c6bdbc157 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -114,7 +114,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -145,7 +145,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -156,7 +156,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb index 779608824ad..ec00b4648fd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb @@ -98,7 +98,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -129,7 +129,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -140,7 +140,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb index 6077f9a5584..0febe89641a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb @@ -98,7 +98,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -129,7 +129,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -140,7 +140,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index a4611d6c7a4..93c5403c9a6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -32,6 +32,7 @@ class ArrayTest attr_accessor :array_array_of_model + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { @@ -119,7 +120,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -150,7 +151,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -161,7 +162,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 8eb06e9ee9f..3d42282a5f4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -79,6 +79,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push("invalid value for 'class_name', class_name cannot be nil.") + end + return invalid_properties end @@ -117,7 +121,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -148,7 +152,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -159,7 +163,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 2edd8b0bbe2..c1256bf9564 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb new file mode 100644 index 00000000000..26e59e35885 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -0,0 +1,199 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'date' + +module Petstore + + class Client + attr_accessor :client + + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'client' => :'client' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'client' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'client') + self.client = attributes[:'client'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + client == o.client + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [client].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index ceaeb2714e9..addfdcfec84 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -79,6 +79,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push("invalid value for 'class_name', class_name cannot be nil.") + end + return invalid_properties end @@ -117,7 +121,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -148,7 +152,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -159,7 +163,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb new file mode 100644 index 00000000000..27b63a806e0 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb @@ -0,0 +1,243 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'date' + +module Petstore + + class EnumArrays + attr_accessor :just_symbol + + attr_accessor :array_enum + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'just_symbol' => :'just_symbol', + :'array_enum' => :'array_enum' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'just_symbol' => :'String', + :'array_enum' => :'Array' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'just_symbol') + self.just_symbol = attributes[:'just_symbol'] + end + + if attributes.has_key?(:'array_enum') + if (value = attributes[:'array_enum']).is_a?(Array) + self.array_enum = value + end + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + just_symbol_validator = EnumAttributeValidator.new('String', [">=", "$"]) + return false unless just_symbol_validator.valid?(@just_symbol) + return true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] just_symbol Object to be assigned + def just_symbol=(just_symbol) + validator = EnumAttributeValidator.new('String', [">=", "$"]) + unless validator.valid?(just_symbol) + fail ArgumentError, "invalid value for 'just_symbol', must be one of #{validator.allowable_values}." + end + @just_symbol = just_symbol + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + just_symbol == o.just_symbol && + array_enum == o.array_enum + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [just_symbol, array_enum].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index ab6e17324d4..e4d0caa19ae 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -171,7 +171,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -202,7 +202,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -213,7 +213,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index 876da790747..75b105e8678 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -157,24 +157,92 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if !@integer.nil? && @integer > 100.0 + invalid_properties.push("invalid value for 'integer', must be smaller than or equal to 100.0.") + end + + if !@integer.nil? && @integer < 10.0 + invalid_properties.push("invalid value for 'integer', must be greater than or equal to 10.0.") + end + + if !@int32.nil? && @int32 > 200.0 + invalid_properties.push("invalid value for 'int32', must be smaller than or equal to 200.0.") + end + + if !@int32.nil? && @int32 < 20.0 + invalid_properties.push("invalid value for 'int32', must be greater than or equal to 20.0.") + end + + if @number.nil? + invalid_properties.push("invalid value for 'number', number cannot be nil.") + end + + if @number > 543.2 + invalid_properties.push("invalid value for 'number', must be smaller than or equal to 543.2.") + end + + if @number < 32.1 + invalid_properties.push("invalid value for 'number', must be greater than or equal to 32.1.") + end + + if !@float.nil? && @float > 987.6 + invalid_properties.push("invalid value for 'float', must be smaller than or equal to 987.6.") + end + + if !@float.nil? && @float < 54.3 + invalid_properties.push("invalid value for 'float', must be greater than or equal to 54.3.") + end + + if !@double.nil? && @double > 123.4 + invalid_properties.push("invalid value for 'double', must be smaller than or equal to 123.4.") + end + + if !@double.nil? && @double < 67.8 + invalid_properties.push("invalid value for 'double', must be greater than or equal to 67.8.") + end + + if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) + invalid_properties.push("invalid value for 'string', must conform to the pattern /[a-z]/i.") + end + + if @byte.nil? + invalid_properties.push("invalid value for 'byte', byte cannot be nil.") + end + + if @date.nil? + invalid_properties.push("invalid value for 'date', date cannot be nil.") + end + + if @password.nil? + invalid_properties.push("invalid value for 'password', password cannot be nil.") + end + + if @password.to_s.length > 64 + invalid_properties.push("invalid value for 'password', the character length must be smaller than or equal to 64.") + end + + if @password.to_s.length < 10 + invalid_properties.push("invalid value for 'password', the character length must be great than or equal to 10.") + end + return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - return false if @integer > 100.0 - return false if @integer < 10.0 - return false if @int32 > 200.0 - return false if @int32 < 20.0 + return false if !@integer.nil? && @integer > 100.0 + return false if !@integer.nil? && @integer < 10.0 + return false if !@int32.nil? && @int32 > 200.0 + return false if !@int32.nil? && @int32 < 20.0 return false if @number.nil? return false if @number > 543.2 return false if @number < 32.1 - return false if @float > 987.6 - return false if @float < 54.3 - return false if @double > 123.4 - return false if @double < 67.8 - return false if @string !~ Regexp.new(/[a-z]/i) + return false if !@float.nil? && @float > 987.6 + return false if !@float.nil? && @float < 54.3 + return false if !@double.nil? && @double > 123.4 + return false if !@double.nil? && @double < 67.8 + return false if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) return false if @byte.nil? return false if @date.nil? return false if @password.nil? @@ -186,15 +254,12 @@ def valid? # Custom attribute writer method with validation # @param [Object] integer Value to be assigned def integer=(integer) - if integer.nil? - fail ArgumentError, "integer cannot be nil" - end - if integer > 100.0 + if !integer.nil? && integer > 100.0 fail ArgumentError, "invalid value for 'integer', must be smaller than or equal to 100.0." end - if integer < 10.0 + if !integer.nil? && integer < 10.0 fail ArgumentError, "invalid value for 'integer', must be greater than or equal to 10.0." end @@ -204,15 +269,12 @@ def integer=(integer) # Custom attribute writer method with validation # @param [Object] int32 Value to be assigned def int32=(int32) - if int32.nil? - fail ArgumentError, "int32 cannot be nil" - end - if int32 > 200.0 + if !int32.nil? && int32 > 200.0 fail ArgumentError, "invalid value for 'int32', must be smaller than or equal to 200.0." end - if int32 < 20.0 + if !int32.nil? && int32 < 20.0 fail ArgumentError, "invalid value for 'int32', must be greater than or equal to 20.0." end @@ -240,15 +302,12 @@ def number=(number) # Custom attribute writer method with validation # @param [Object] float Value to be assigned def float=(float) - if float.nil? - fail ArgumentError, "float cannot be nil" - end - if float > 987.6 + if !float.nil? && float > 987.6 fail ArgumentError, "invalid value for 'float', must be smaller than or equal to 987.6." end - if float < 54.3 + if !float.nil? && float < 54.3 fail ArgumentError, "invalid value for 'float', must be greater than or equal to 54.3." end @@ -258,15 +317,12 @@ def float=(float) # Custom attribute writer method with validation # @param [Object] double Value to be assigned def double=(double) - if double.nil? - fail ArgumentError, "double cannot be nil" - end - if double > 123.4 + if !double.nil? && double > 123.4 fail ArgumentError, "invalid value for 'double', must be smaller than or equal to 123.4." end - if double < 67.8 + if !double.nil? && double < 67.8 fail ArgumentError, "invalid value for 'double', must be greater than or equal to 67.8." end @@ -276,11 +332,8 @@ def double=(double) # Custom attribute writer method with validation # @param [Object] string Value to be assigned def string=(string) - if string.nil? - fail ArgumentError, "string cannot be nil" - end - if @string !~ Regexp.new(/[a-z]/i) + if !string.nil? && string !~ Regexp.new(/[a-z]/i) fail ArgumentError, "invalid value for 'string', must conform to the pattern /[a-z]/i." end @@ -343,7 +396,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -374,7 +427,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -385,7 +438,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb index 046325dbced..4060aacc767 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb b/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb index a3a44b28cfe..442a0e26ed8 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb @@ -159,7 +159,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb new file mode 100644 index 00000000000..4924d2f82b5 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -0,0 +1,199 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'date' + +module Petstore + + class List + attr_accessor :_123_list + + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'_123_list' => :'123-list' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'_123_list' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'123-list') + self._123_list = attributes[:'123-list'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + _123_list == o._123_list + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [_123_list].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index 3c4cf4243c0..1cbde73b242 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -28,8 +28,6 @@ module Petstore class MapTest attr_accessor :map_map_of_string - attr_accessor :map_map_of_enum - attr_accessor :map_of_enum_string class EnumAttributeValidator @@ -58,7 +56,6 @@ def valid?(value) def self.attribute_map { :'map_map_of_string' => :'map_map_of_string', - :'map_map_of_enum' => :'map_map_of_enum', :'map_of_enum_string' => :'map_of_enum_string' } end @@ -67,7 +64,6 @@ def self.attribute_map def self.swagger_types { :'map_map_of_string' => :'Hash>', - :'map_map_of_enum' => :'Hash>', :'map_of_enum_string' => :'Hash' } end @@ -86,12 +82,6 @@ def initialize(attributes = {}) end end - if attributes.has_key?(:'map_map_of_enum') - if (value = attributes[:'map_map_of_enum']).is_a?(Array) - self.map_map_of_enum = value - end - end - if attributes.has_key?(:'map_of_enum_string') if (value = attributes[:'map_of_enum_string']).is_a?(Array) self.map_of_enum_string = value @@ -110,40 +100,15 @@ def list_invalid_properties # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - map_map_of_enum_validator = EnumAttributeValidator.new('Hash>', []) - return false unless map_map_of_enum_validator.valid?(@map_map_of_enum) - map_of_enum_string_validator = EnumAttributeValidator.new('Hash', []) - return false unless map_of_enum_string_validator.valid?(@map_of_enum_string) return true end - # Custom attribute writer method checking allowed values (enum). - # @param [Object] map_map_of_enum Object to be assigned - def map_map_of_enum=(map_map_of_enum) - validator = EnumAttributeValidator.new('Hash>', []) - unless validator.valid?(map_map_of_enum) - fail ArgumentError, "invalid value for 'map_map_of_enum', must be one of #{validator.allowable_values}." - end - @map_map_of_enum = map_map_of_enum - end - - # Custom attribute writer method checking allowed values (enum). - # @param [Object] map_of_enum_string Object to be assigned - def map_of_enum_string=(map_of_enum_string) - validator = EnumAttributeValidator.new('Hash', []) - unless validator.valid?(map_of_enum_string) - fail ArgumentError, "invalid value for 'map_of_enum_string', must be one of #{validator.allowable_values}." - end - @map_of_enum_string = map_of_enum_string - end - # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && map_map_of_string == o.map_map_of_string && - map_map_of_enum == o.map_map_of_enum && map_of_enum_string == o.map_of_enum_string end @@ -156,7 +121,7 @@ def eql?(o) # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [map_map_of_string, map_map_of_enum, map_of_enum_string].hash + [map_map_of_string, map_of_enum_string].hash end # Builds the object from hash @@ -165,7 +130,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -196,7 +161,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -207,7 +172,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| 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 e87726056fe..edcdc5493a4 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 @@ -116,7 +116,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -147,7 +147,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -158,7 +158,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb index 3a519731281..08035465418 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 448610807c6..2b5db8872ee 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index dd6978fec9a..47b1319b638 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -85,6 +85,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @name.nil? + invalid_properties.push("invalid value for 'name', name cannot be nil.") + end + return invalid_properties end @@ -124,7 +128,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -155,7 +159,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -166,7 +170,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb index 4b70b090df8..b1bdd34e3ca 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 2b6aa895718..2dcd1b6063e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -177,7 +177,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -208,7 +208,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -219,7 +219,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index b74bba64192..18ad44b0830 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -127,6 +127,14 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @name.nil? + invalid_properties.push("invalid value for 'name', name cannot be nil.") + end + + if @photo_urls.nil? + invalid_properties.push("invalid value for 'photo_urls', photo_urls cannot be nil.") + end + return invalid_properties end @@ -181,7 +189,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -212,7 +220,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -223,7 +231,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb index 3be06c72ffb..3124c15f6ed 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 40e8f2ed692..b7e2c9262f0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index d7a351d3dbe..2174ba9a1b7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 5d7467ad970..0553d61e85d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -160,7 +160,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) @@ -191,7 +191,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false @@ -202,7 +202,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 4075ba0fc2d..9d4aa367b9c 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -36,6 +36,7 @@ Gem::Specification.new do |s| s.summary = "Swagger Petstore Ruby Gem" s.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: \" \\" s.license = "Apache 2.0" + s.required_ruby_version = ">= 1.9" s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' s.add_runtime_dependency 'json', '~> 1.8', '>= 1.8.3' diff --git a/samples/client/petstore/ruby/spec/base_object_spec.rb b/samples/client/petstore/ruby/spec/base_object_spec.rb index 5b84351f7b8..115a1c0e040 100644 --- a/samples/client/petstore/ruby/spec/base_object_spec.rb +++ b/samples/client/petstore/ruby/spec/base_object_spec.rb @@ -51,7 +51,7 @@ def self.swagger_types int_arr_map: {'int_arr' => [123, 456]}, pet_arr_map: {'pet_arr' => [{name: 'Kitty'}]}, boolean_true_arr: [true, "true", "TruE", 1, "y", "yes", "1", "t", "T"], - boolean_false_arr: [false, "", 0, "0", "f", nil, "null"], + boolean_false_arr: [false, "", 0, "0", "f", nil, "null", "\ntrue\n"], } end diff --git a/samples/client/petstore/ruby/spec/models/client_spec.rb b/samples/client/petstore/ruby/spec/models/client_spec.rb new file mode 100644 index 00000000000..d49fd5fc85f --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/client_spec.rb @@ -0,0 +1,53 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Client +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Client' do + before do + # run before each test + @instance = Petstore::Client.new + end + + after do + # run after each test + end + + describe 'test an instance of Client' do + it 'should create an instact of Client' do + expect(@instance).to be_instance_of(Petstore::Client) + end + end + describe 'test attribute "client"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb b/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb new file mode 100644 index 00000000000..992eb750d30 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/enum_arrays_spec.rb @@ -0,0 +1,67 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::EnumArrays +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'EnumArrays' do + before do + # run before each test + @instance = Petstore::EnumArrays.new + end + + after do + # run after each test + end + + describe 'test an instance of EnumArrays' do + it 'should create an instact of EnumArrays' do + expect(@instance).to be_instance_of(Petstore::EnumArrays) + end + end + describe 'test attribute "array_enum"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + #validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', []) + #validator.allowable_values.each do |value| + # expect { @instance.array_enum = value }.not_to raise_error + #end + end + end + + describe 'test attribute "array_array_enum"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + #validator = Petstore::EnumTest::EnumAttributeValidator.new('Array>', []) + #validator.allowable_values.each do |value| + # expect { @instance.array_array_enum = value }.not_to raise_error + #end + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/list_spec.rb b/samples/client/petstore/ruby/spec/models/list_spec.rb new file mode 100644 index 00000000000..0ae7af9569b --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/list_spec.rb @@ -0,0 +1,53 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::List +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'List' do + before do + # run before each test + @instance = Petstore::List.new + end + + after do + # run after each test + end + + describe 'test an instance of List' do + it 'should create an instact of List' do + expect(@instance).to be_instance_of(Petstore::List) + end + end + describe 'test attribute "_123_list"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + diff --git a/samples/client/petstore/scala/.swagger-codegen-ignore b/samples/client/petstore/scala/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/scala/.swagger-codegen-ignore +++ b/samples/client/petstore/scala/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/scala/gradlew.bat b/samples/client/petstore/scala/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/scala/gradlew.bat +++ b/samples/client/petstore/scala/gradlew.bat @@ -1,90 +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 +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index 5b036cd8fc1..27055cbbdc6 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.8 + 1.5.9 1.0.5 1.0.0 2.4.2 diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index 66ff610e9b3..17b40913a28 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -53,29 +53,27 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body Pet object that needs to be added to the store * @return void */ - def addPet (body: Pet) = { + def addPet(body: Pet) = { // create path and map variables - val path = "/pet".replaceAll("\\{format\\}","json") - val contentTypes = List("application/json", "application/xml", "application/json") + val path = "/pet".replaceAll("\\{format\\}", "json") + + val contentTypes = List("application/json", "application/xml") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->addPet") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -96,30 +94,26 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param apiKey (optional) * @return void */ - def deletePet (petId: Long, apiKey: String) = { + def deletePet(petId: Long, apiKey: Option[String] = None) = { // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - + val path = "/pet/{petId}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - - headerParams += "api_key" -> apiKey + + apiKey.map(paramVal => headerParams += "api_key" -> paramVal) var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -139,30 +133,28 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param status Status values that need to be considered for filter * @return List[Pet] */ - def findPetsByStatus (status: List[String]) : Option[List[Pet]] = { + def findPetsByStatus(status: List[String]): Option[List[Pet]] = { // create path and map variables - val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") + val path = "/pet/findByStatus".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus") - if(String.valueOf(status) != "null") queryParams += "status" -> status.toString - + queryParams += "status" -> status.toString + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -183,30 +175,28 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param tags Tags to filter by * @return List[Pet] */ - def findPetsByTags (tags: List[String]) : Option[List[Pet]] = { + def findPetsByTags(tags: List[String]): Option[List[Pet]] = { // create path and map variables - val path = "/pet/findByTags".replaceAll("\\{format\\}","json") + val path = "/pet/findByTags".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags") - if(String.valueOf(tags) != "null") queryParams += "tags" -> tags.toString - + queryParams += "tags" -> tags.toString + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -227,29 +217,25 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param petId ID of pet to return * @return Pet */ - def getPetById (petId: Long) : Option[Pet] = { + def getPetById(petId: Long): Option[Pet] = { // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - + val path = "/pet/{petId}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -270,29 +256,27 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body Pet object that needs to be added to the store * @return void */ - def updatePet (body: Pet) = { + def updatePet(body: Pet) = { // create path and map variables - val path = "/pet".replaceAll("\\{format\\}","json") - val contentTypes = List("application/json", "application/xml", "application/json") + val path = "/pet".replaceAll("\\{format\\}", "json") + + val contentTypes = List("application/json", "application/xml") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->updatePet") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -314,35 +298,29 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param status Updated status of the pet (optional) * @return void */ - def updatePetWithForm (petId: Long, name: String, status: String) = { + def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = { // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) + val path = "/pet/{petId}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - - val contentTypes = List("application/x-www-form-urlencoded", "application/json") + val contentTypes = List("application/x-www-form-urlencoded") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - - mp.field("name", name.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) - - mp.field("status", status.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart + name.map(paramVal => mp.field("name", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) + status.map(paramVal => mp.field("status", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) postBody = mp - } - else { - formParams += "name" -> name.toString() - formParams += "status" -> status.toString() + } else { + name.map(paramVal => formParams += "name" -> paramVal.toString) + status.map(paramVal => formParams += "status" -> paramVal.toString) } try { @@ -364,36 +342,29 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param file file to upload (optional) * @return ApiResponse */ - def uploadFile (petId: Long, additionalMetadata: String, file: File) : Option[ApiResponse] = { + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = { // create path and map variables - val path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) + val path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - - val contentTypes = List("multipart/form-data", "application/json") + val contentTypes = List("multipart/form-data") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - - mp.field("additionalMetadata", additionalMetadata.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) - - mp.field("file", file.getName) - mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart + additionalMetadata.map(paramVal => mp.field("additionalMetadata", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) + file.map(fileVal => mp.field("file", fileVal.getName)) + file.map(paramVal => mp.bodyPart(new FileDataBodyPart("file", paramVal, MediaType.MULTIPART_FORM_DATA_TYPE))) postBody = mp - } - else { - formParams += "additionalMetadata" -> additionalMetadata.toString() - + } else { + additionalMetadata.map(paramVal => formParams += "additionalMetadata" -> paramVal.toString) } try { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 2d184550d13..5388a9dfc10 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -51,29 +51,27 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param orderId ID of the order that needs to be deleted * @return void */ - def deleteOrder (orderId: String) = { + def deleteOrder(orderId: String) = { // create path and map variables - val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) - + val path = "/store/order/{orderId}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder") + + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -92,27 +90,25 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * Returns a map of status codes to quantities * @return Map[String, Integer] */ - def getInventory () : Option[Map[String, Integer]] = { + def getInventory(): Option[Map[String, Integer]] = { // create path and map variables - val path = "/store/inventory".replaceAll("\\{format\\}","json") + val path = "/store/inventory".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -133,29 +129,25 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param orderId ID of pet that needs to be fetched * @return Order */ - def getOrderById (orderId: Long) : Option[Order] = { + def getOrderById(orderId: Long): Option[Order] = { // create path and map variables - val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) - + val path = "/store/order/{orderId}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -176,29 +168,27 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body order placed for purchasing the pet * @return Order */ - def placeOrder (body: Order) : Option[Order] = { + def placeOrder(body: Order): Option[Order] = { // create path and map variables - val path = "/store/order".replaceAll("\\{format\\}","json") + val path = "/store/order".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (body == null) throw new Exception("Missing required parameter 'body' when calling StoreApi->placeOrder") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala index db6ada19ebc..14e642976f8 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -51,29 +51,27 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body Created user object * @return void */ - def createUser (body: User) = { + def createUser(body: User) = { // create path and map variables - val path = "/user".replaceAll("\\{format\\}","json") + val path = "/user".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUser") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -93,29 +91,27 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body List of user object * @return void */ - def createUsersWithArrayInput (body: List[User]) = { + def createUsersWithArrayInput(body: List[User]) = { // create path and map variables - val path = "/user/createWithArray".replaceAll("\\{format\\}","json") + val path = "/user/createWithArray".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithArrayInput") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -135,29 +131,27 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body List of user object * @return void */ - def createUsersWithListInput (body: List[User]) = { + def createUsersWithListInput(body: List[User]) = { // create path and map variables - val path = "/user/createWithList".replaceAll("\\{format\\}","json") + val path = "/user/createWithList".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithListInput") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -177,29 +171,27 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param username The name that needs to be deleted * @return void */ - def deleteUser (username: String) = { + def deleteUser(username: String) = { // create path and map variables - val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) - + val path = "/user/{username}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser") + + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -219,29 +211,27 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ - def getUserByName (username: String) : Option[User] = { + def getUserByName(username: String): Option[User] = { // create path and map variables - val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) - + val path = "/user/{username}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName") + + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -263,29 +253,31 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param password The password for login in clear text * @return String */ - def loginUser (username: String, password: String) : Option[String] = { + def loginUser(username: String, password: String): Option[String] = { // create path and map variables - val path = "/user/login".replaceAll("\\{format\\}","json") + val path = "/user/login".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - if(String.valueOf(username) != "null") queryParams += "username" -> username.toString -if(String.valueOf(password) != "null") queryParams += "password" -> password.toString - + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser") + + if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser") + + queryParams += "username" -> username.toString + queryParams += "password" -> password.toString + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -305,27 +297,25 @@ if(String.valueOf(password) != "null") queryParams += "password" -> password.toS * * @return void */ - def logoutUser () = { + def logoutUser() = { // create path and map variables - val path = "/user/logout".replaceAll("\\{format\\}","json") + val path = "/user/logout".replaceAll("\\{format\\}", "json") + val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { @@ -346,31 +336,29 @@ if(String.valueOf(password) != "null") queryParams += "password" -> password.toS * @param body Updated user object * @return void */ - def updateUser (username: String, body: User) = { + def updateUser(username: String, body: User) = { // create path and map variables - val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) - + val path = "/user/{username}".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) val contentTypes = List("application/json") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser") + if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->updateUser") - + var postBody: AnyRef = body - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart postBody = mp - } - else { + } else { } try { 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 49721a758a0..99e93a5d348 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 @@ -25,9 +25,8 @@ package io.swagger.client.model - - case class ApiResponse ( code: Integer, -_type: String, -message: String) + _type: String, + message: String +) 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 c8843e065e7..3499402cef3 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 @@ -25,8 +25,7 @@ package io.swagger.client.model - - case class Category ( id: Long, -name: String) + name: String +) 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 12fe2850ec4..cffd2211409 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 @@ -26,13 +26,12 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Order ( id: Long, -petId: Long, -quantity: Integer, -shipDate: DateTime, -/* Order Status */ + petId: Long, + quantity: Integer, + shipDate: DateTime, + /* Order Status */ status: String, -complete: Boolean) + complete: Boolean +) 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 43420b1a9e0..fc8f5e09764 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 @@ -25,13 +25,12 @@ package io.swagger.client.model - - case class Pet ( id: Long, -category: Category, -name: String, -photoUrls: List[String], -tags: List[Tag], -/* pet status in the store */ - status: String) + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + /* pet status in the store */ + status: String +) 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 6cc351ba45b..bb2bfae71e3 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 @@ -25,8 +25,7 @@ package io.swagger.client.model - - case class Tag ( id: Long, -name: String) + name: String +) 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 4e80b6c6697..cbbbded06f0 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 @@ -25,15 +25,14 @@ package io.swagger.client.model - - case class User ( id: Long, -username: String, -firstName: String, -lastName: String, -email: String, -password: String, -phone: String, -/* User Status */ - userStatus: Integer) + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + /* User Status */ + userStatus: Integer +) diff --git a/samples/client/petstore/spring-cloud/.swagger-codegen-ignore b/samples/client/petstore/spring-cloud/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/spring-cloud/.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/spring-cloud/LICENSE b/samples/client/petstore/spring-cloud/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/spring-cloud/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/spring-cloud/README.md b/samples/client/petstore/spring-cloud/README.md new file mode 100644 index 00000000000..0d2d58540db --- /dev/null +++ b/samples/client/petstore/spring-cloud/README.md @@ -0,0 +1,53 @@ +# swagger-petstore-spring-cloud + +## 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-spring-cloud + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-spring-cloud:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + +mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-spring-cloud-1.0.0.jar +* target/lib/*.jar diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml new file mode 100644 index 00000000000..159fdae3e61 --- /dev/null +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -0,0 +1,68 @@ + + 4.0.0 + io.swagger + swagger-petstore-spring-cloud + jar + swagger-petstore-spring-cloud + 1.0.0 + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + + + src/main/java + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR2 + pom + import + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + org.springframework.cloud + spring-cloud-starter-feign + + + org.springframework.cloud + spring-cloud-security + + + org.springframework.security.oauth + spring-security-oauth2 + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + + + org.springframework.boot + spring-boot-starter-test + test + + + \ No newline at end of file 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 new file mode 100644 index 00000000000..5dbd5284d25 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,185 @@ +package io.swagger.api; + +import io.swagger.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "pet", description = "the pet API") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body +); + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + +, +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + +); + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + +); + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + +); + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + +); + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body +); + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/x-www-form-urlencoded", + method = RequestMethod.POST) + ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + +, + + +@ApiParam(value = "Updated name of the pet" ) @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", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = "application/json", + consumes = "multipart/form-data", + method = RequestMethod.POST) + ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + +, + + +@ApiParam(value = "Additional data to pass to server" ) @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/PetApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java new file mode 100644 index 00000000000..64bd0b2f70c --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java @@ -0,0 +1,8 @@ +package io.swagger.api; + +import org.springframework.cloud.netflix.feign.FeignClient; +import io.swagger.configuration.ClientConfiguration; + +@FeignClient(name="${swaggerPetstore.name:swaggerPetstore}", url="${swaggerPetstore.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) +public interface PetApiClient extends PetApi { +} \ No newline at end of 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 new file mode 100644 index 00000000000..cd63106117c --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,77 @@ +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.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "store", description = "the store API") +public interface StoreApi { + + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + +); + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> getInventory(); + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + +); + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body +); + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java new file mode 100644 index 00000000000..99321fe75ee --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java @@ -0,0 +1,8 @@ +package io.swagger.api; + +import org.springframework.cloud.netflix.feign.FeignClient; +import io.swagger.configuration.ClientConfiguration; + +@FeignClient(name="${swaggerPetstore.name:swaggerPetstore}", url="${swaggerPetstore.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) +public interface StoreApiClient extends StoreApi { +} \ No newline at end of file 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 new file mode 100644 index 00000000000..547419cb04a --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,134 @@ +package io.swagger.api; + +import io.swagger.model.User; +import java.util.List; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "user", description = "the user API") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUser( + +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body +); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + +); + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + +); + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username + + +,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + +); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity logoutUser(); + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + +, + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body +); + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java new file mode 100644 index 00000000000..1d8783803f3 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java @@ -0,0 +1,8 @@ +package io.swagger.api; + +import org.springframework.cloud.netflix.feign.FeignClient; +import io.swagger.configuration.ClientConfiguration; + +@FeignClient(name="${swaggerPetstore.name:swaggerPetstore}", url="${swaggerPetstore.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) +public interface UserApiClient extends UserApi { +} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java new file mode 100644 index 00000000000..b83fd9c6bac --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java @@ -0,0 +1,31 @@ +package io.swagger.configuration; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Util; + + +public class ApiKeyRequestInterceptor implements RequestInterceptor { + private final String location; + private final String name; + private String value; + + public ApiKeyRequestInterceptor(String location, String name, String value) { + Util.checkNotNull(location, "location", new Object[0]); + Util.checkNotNull(name, "name", new Object[0]); + Util.checkNotNull(value, "value", new Object[0]); + this.location = location; + this.name = name; + this.value = value; + } + + @Override + public void apply(RequestTemplate requestTemplate) { + if(location.equals("header")) { + requestTemplate.header(name, value); + } else if(location.equals("query")) { + requestTemplate.query(name, value); + } + } + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java new file mode 100644 index 00000000000..9e68822a61e --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java @@ -0,0 +1,49 @@ +package io.swagger.configuration; + +import feign.Logger; +import feign.auth.BasicAuthRequestInterceptor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; +import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; +import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails; +import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +@Configuration +@EnableConfigurationProperties +public class ClientConfiguration { + + @Value("${ swaggerPetstore.security.apiKey.key:}") + private String apiKeyKey; + + @Bean + @ConditionalOnProperty(name = "swaggerPetstore.security.apiKey.key") + public ApiKeyRequestInterceptor apiKeyRequestInterceptor() { + return new ApiKeyRequestInterceptor("header", "api_key", this.apiKeyKey); + } + + @Bean + @ConditionalOnProperty("swaggerPetstore.security.petstoreAuth.client-id") + public OAuth2FeignRequestInterceptor petstoreAuthRequestInterceptor() { + return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), petstoreAuthResourceDetails()); + } + + @Bean + @ConditionalOnProperty("swaggerPetstore.security.petstoreAuth.client-id") + @ConfigurationProperties("swaggerPetstore.security.petstoreAuth") + public ImplicitResourceDetails petstoreAuthResourceDetails() { + ImplicitResourceDetails details = new ImplicitResourceDetails(); + details.setUserAuthorizationUri("http://petstore.swagger.io/api/oauth/dialog"); + return details; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..3c8cf28ec23 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A category for a pet + */ +@ApiModel(description = "A category for a pet") + +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/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..6d6641bfe9a --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,121 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Describes the result of uploading an image resource + */ +@ApiModel(description = "Describes the result of uploading an image resource") + +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/spring-cloud/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..ee99fb04426 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,225 @@ +package io.swagger.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.joda.time.DateTime; + +/** + * An order for a pets from the pet store + */ +@ApiModel(description = "An order for a pets from the pet store") + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @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(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..5cdfc19b38e --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,238 @@ +package io.swagger.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.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +/** + * A pet for sale in the pet store + */ +@ApiModel(description = "A pet for sale in the pet store") + +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 = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @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) { + 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/spring-cloud/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..7fd1757b21c --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A tag for a pet + */ +@ApiModel(description = "A tag for a pet") + +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/spring-cloud/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..f14694154b4 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java @@ -0,0 +1,236 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A User who is purchasing from the pet store + */ +@ApiModel(description = "A User who is purchasing from the pet store") + +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/spring-cloud/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 00000000000..bf5a476ab29 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java new file mode 100644 index 00000000000..a08dccc2a60 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java @@ -0,0 +1,207 @@ +package io.swagger.api; + +import feign.FeignException; +import io.swagger.TestUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import io.swagger.model.Category; +import io.swagger.model.Pet; +import io.swagger.model.Tag; +import org.junit.*; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = PetApiTest.Application.class) +public class PetApiTest { + + @Autowired + private PetApiClient client; + + @Test + public void testCreateAndGetPet() { + Pet pet = createRandomPet(); + client.addPet(pet); + ResponseEntity rp = client.getPetById(pet.getId()); + Pet fetched = rp.getBody(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + client.updatePet(pet); + + Pet fetched = client.getPetById(pet.getId()).getBody(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Ignore + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + client.updatePet(pet); + + List pets = client.findPetsByStatus(Arrays.asList(new String[]{"available"})).getBody(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Ignore + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + client.updatePet(pet); + + List pets = client.findPetsByTags(Arrays.asList(new String[]{"friendly"})).getBody(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + client.addPet(pet); + + Pet fetched = client.getPetById(pet.getId()).getBody(); + + client.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = client.getPetById(fetched.getId()).getBody(); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + client.addPet(pet); + + Pet fetched = client.getPetById(pet.getId()).getBody(); + client.deletePet(fetched.getId(), null); + + try { + client.getPetById(fetched.getId()); + fail("expected an error"); + } catch (FeignException e) { + assertTrue(e.getMessage().startsWith("status 404 ")); + } + } + + @Ignore("Multipart form is not supported by spring-cloud yet.") + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + client.addPet(pet); + + MockMultipartFile filePart = new MockMultipartFile("file", "bar".getBytes()); + client.uploadFile(pet.getId(), "a test file", filePart); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + + @SpringBootApplication + @EnableFeignClients + protected static class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(Application.class).run(args); + } + } + + + + + + +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java new file mode 100644 index 00000000000..223289baf15 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java @@ -0,0 +1,89 @@ +package io.swagger.api; + +import feign.FeignException; +import io.swagger.TestUtils; +import io.swagger.model.Order; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.lang.reflect.Field; +import java.util.Map; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = StoreApiTest.Application.class) +public class StoreApiTest { + + @Autowired + private StoreApiClient client; + + @Test + public void testGetInventory() { + Map inventory = client.getInventory().getBody(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() { + Order order = createOrder(); + client.placeOrder(order); + + Order fetched = client.getOrderById(order.getId()).getBody(); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().toInstant(), fetched.getShipDate().toInstant()); + } + + @Test + public void testDeleteOrder() { + Order order = createOrder(); + client.placeOrder(order); + + Order fetched = client.getOrderById(order.getId()).getBody(); + assertEquals(fetched.getId(), order.getId()); + + client.deleteOrder(String.valueOf(order.getId())); + + try { + client.getOrderById(order.getId()); + fail("expected an error"); + } catch (FeignException e) { + assertTrue(e.getMessage().startsWith("status 404 ")); + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(org.joda.time.DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; + } + + @SpringBootApplication + @EnableFeignClients + protected static class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(StoreApiTest.Application.class).run(args); + } + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java new file mode 100644 index 00000000000..4fb9b5e1a12 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java @@ -0,0 +1,97 @@ +package io.swagger.api; + +import io.swagger.TestUtils; +import io.swagger.model.User; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.Arrays; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = UserApiTest.Application.class) + +public class UserApiTest { + + @Autowired + private UserApiClient client; + + @Test + public void testCreateUser() { + User user = createUser(); + + client.createUser(user); + + User fetched = client.getUserByName(user.getUsername()).getBody(); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + client.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = client.getUserByName(user1.getUsername()).getBody(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + client.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = client.getUserByName(user1.getUsername()).getBody(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() { + User user = createUser(); + client.createUser(user); + + String token = client.loginUser(user.getUsername(), user.getPassword()).getBody(); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() { + client.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } + + @SpringBootApplication + @EnableFeignClients + protected static class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(UserApiTest.Application.class).run(args); + } + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/resources/application.yml b/samples/client/petstore/spring-cloud/src/test/resources/application.yml new file mode 100644 index 00000000000..07a52419295 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/resources/application.yml @@ -0,0 +1,10 @@ +spring: + application: + name: petstore-test + +feign.hystrix.enabled: false + +logging.level.io.swagger.api: + PetApiClient: DEBUG + StoreApiClient: DEBUG + UserApiClient: DEBUG diff --git a/samples/client/petstore/spring-stubs/.swagger-codegen-ignore b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/spring-stubs/.swagger-codegen-ignore +++ b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/spring-stubs/pom.xml b/samples/client/petstore/spring-stubs/pom.xml index d6e6b09a2ed..851d0f3018c 100644 --- a/samples/client/petstore/spring-stubs/pom.xml +++ b/samples/client/petstore/spring-stubs/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-spring-server + swagger-spring jar - swagger-spring-server + swagger-spring 1.0.0 1.7 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 40c6924d115..6acd0c19d80 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 @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -26,14 +26,18 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet", produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +); @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { @@ -41,15 +45,22 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + + +, +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + + +); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -57,7 +68,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @@ -65,7 +76,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + + +); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -73,7 +88,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @@ -81,12 +96,16 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + + +); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -95,7 +114,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + + +); @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { @@ -103,7 +126,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -112,7 +135,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru produces = "application/json", consumes = "application/json", method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +); @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { @@ -120,16 +147,26 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = "application/json", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, - @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + + +, + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -137,15 +174,25 @@ ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs t @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = "application/json", consumes = "multipart/form-data", method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + + +, + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +); } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java index 88c19d8540e..2dc04ca4efd 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 @@ -20,7 +20,7 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @@ -28,12 +28,16 @@ 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); + ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + + +); @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -43,7 +47,7 @@ public interface StoreApi { ResponseEntity> getInventory(); - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -52,10 +56,14 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + +); - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) @@ -63,6 +71,10 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body + +); } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java index 706d1343038..0e5a8bb9cae 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 @@ -20,37 +20,49 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + ResponseEntity createUser( +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) +); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -58,10 +70,14 @@ 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); + ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + + +); - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -70,10 +86,14 @@ 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); + ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + + +); - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @@ -81,11 +101,18 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + +,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + + +); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -95,7 +122,7 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re ResponseEntity logoutUser(); - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -103,7 +130,14 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re produces = "application/json", consumes = "application/json", method = RequestMethod.PUT) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + + +, + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body + +); } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java index 67bc75b3b10..3c8cf28ec23 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java @@ -2,56 +2,61 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * A category for a pet + */ +@ApiModel(description = "A category for a pet") 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +64,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +88,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..6d6641bfe9a 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,82 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * Describes the result of uploading an image resource + */ +@ApiModel(description = "Describes the result of uploading an image resource") 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 = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +85,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +111,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java index 55859fc4089..ee99fb04426 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java @@ -2,27 +2,38 @@ 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.joda.time.DateTime; - - - - +/** + * An order for a pets from the pet store + */ +@ApiModel(description = "An order for a pets from the pet store") public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private DateTime shipDate = null; + @JsonProperty("shipDate") + private DateTime shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +45,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +183,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -186,7 +215,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java index 24092cbee25..5cdfc19b38e 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ 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; @@ -10,23 +11,35 @@ import java.util.ArrayList; import java.util.List; - - - - +/** + * A pet for sale in the pet store + */ +@ApiModel(description = "A pet for sale in the pet store") 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(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +51,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +196,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -189,7 +228,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java index f26d84e74b2..7fd1757b21c 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java @@ -2,56 +2,61 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * A tag for a pet + */ +@ApiModel(description = "A tag for a pet") 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +64,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +88,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java index 5dc291a7889..f14694154b4 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java @@ -2,165 +2,187 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * A User who is purchasing from the pet store + */ +@ApiModel(description = "A User who is purchasing from the pet store") 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +190,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -204,7 +226,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore +++ b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/swift/.swagger-codegen-ignore b/samples/client/petstore/swift/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/swift/.swagger-codegen-ignore +++ b/samples/client/petstore/swift/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/swift/default/PetstoreClient.podspec b/samples/client/petstore/swift/default/PetstoreClient.podspec index 86fa60dd1c6..baff671c998 100644 --- a/samples/client/petstore/swift/default/PetstoreClient.podspec +++ b/samples/client/petstore/swift/default/PetstoreClient.podspec @@ -4,10 +4,10 @@ Pod::Spec.new do |s| s.osx.deployment_target = '10.9' s.version = '0.0.1' s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } - s.authors = + s.authors = '' s.license = 'Apache License, Version 2.0' s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' - s.dependency 'Alamofire', '~> 3.1.5' + s.dependency 'Alamofire', '~> 3.4.1' end diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift index 96eead0d8dd..ab0ea147e4f 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift @@ -37,6 +37,9 @@ public class RequestBuilder { let method: String let URLString: String + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index cdbd4323e70..a64e2da9b57 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -104,17 +104,17 @@ public class PetAPI: APIBase { /** Finds Pets by status - GET /pet/findByStatus - - Multiple status values can be provided with comma seperated strings + - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -153,24 +153,24 @@ public class PetAPI: APIBase { /** Finds Pets by tags - GET /pet/findByTags - - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -179,21 +179,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -202,7 +202,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -242,26 +242,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -270,21 +270,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -293,7 +293,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 1c575eb79f8..c51d8d37357 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,12 +67,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int32]> */ @@ -108,36 +108,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -176,36 +176,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index a7497487f85..d6df7754683 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,16 +167,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -185,17 +185,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -204,7 +204,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -244,8 +244,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2faa0a6f24d..4ea47d8926c 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -12,8 +12,33 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { } } +public struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = dispatch_queue_create("SynchronizedDictionary", DISPATCH_QUEUE_CONCURRENT) + + public subscript(key: K) -> V? { + get { + var value: V? + + dispatch_sync(queue) { + value = self.dictionary[key] + } + + return value + } + + set { + dispatch_barrier_sync(queue) { + self.dictionary[key] = newValue + } + } + } + +} + // Store manager to retain its reference -private var managerStore: [String: Alamofire.Manager] = [:] +private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { @@ -57,15 +82,22 @@ class AlamofireRequestBuilder: RequestBuilder { encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: { encodingResult in switch encodingResult { - case .Success(let upload, _, _): - self.processRequest(upload, managerId, completion) + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): - completion(response: nil, error: encodingError) + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) } } ) } else { - processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) } } @@ -75,30 +107,99 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.validate().responseJSON(options: .AllowFragments) { response in - managerStore.removeValueForKey(managerId) + let cleanupRequest = { + managerStore[managerId] = nil + } - if response.result.isFailure { - completion(response: nil, error: response.result.error) - return - } + let validatedRequest = request.validate() - if () is T { - completion(response: Response(response: response.response!, body: () as! T), error: nil) - return - } - if let json: AnyObject = response.result.value { - let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), error: nil) - return - } else if "" is T { - // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release - // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), error: nil) - return - } + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) + case is NSData.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) + } } } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift index fed87969388..c974cc40b36 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -58,11 +58,17 @@ extension Dictionary: JSONEncodable { } } +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} private let dateFormatter: NSDateFormatter = { - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt }() extension NSDate: JSONEncodable { @@ -71,4 +77,10 @@ extension NSDate: JSONEncodable { } } +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index cad60a236a7..32175b605a3 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -10,18 +10,22 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + public class Response { public let statusCode: Int public let header: [String: String] - public let body: T + public let body: T? - public init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T?) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { @@ -62,9 +66,15 @@ class Decoders { if T.self is Int64.Type && source is NSNumber { return source.longLongValue as! T; } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } if source is T { return source as! T } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } let key = "\(T.self)" if let decoder = decoders[key] { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE index bf300e4482e..4cfbf72a4d8 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md index bcc0ff4bd05..e0acf722db1 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md @@ -1,7 +1,7 @@ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) -[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) @@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift. - [x] Comprehensive Unit Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. + ## Requirements - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 7.2+ +- Xcode 7.3+ ## Migration Guides @@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo ```ruby source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '8.0' +platform :ios, '9.0' use_frameworks! -pod 'Alamofire', '~> 3.0' +target '' do + pod 'Alamofire', '~> 3.4' +end ``` Then, run the following command: @@ -86,7 +95,7 @@ $ brew install carthage To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl -github "Alamofire/Alamofire" ~> 3.0 +github "Alamofire/Alamofire" ~> 3.4 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. @@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) > Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + ### Response Serialization **Built-in Response Methods** @@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .response { request, response, data, error in print(request) print(response) @@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) } ``` -> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. #### Response Data Handler ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .responseData { response in print(response.request) print(response.response) @@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") @@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get") ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseJSON { response in debugPrint(response) } @@ -221,6 +266,7 @@ Response handlers can even be chained: ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Response String: \(response.result.value)") } @@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global ` ```swift let headers = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", - "Content-Type": "application/x-www-form-urlencoded" + "Accept": "application/json" ] Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) @@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) print("Total bytes written on main queue: \(totalBytesWritten)") } } + .validate() .responseJSON { response in debugPrint(response) } @@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") } ``` -### Validation - -By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. - -#### Manual Validation - -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { response in - print(response) - } -``` - -#### Automatic Validation +### Timeline -Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .responseJSON { response in - switch response.result { - case .Success: - print("Validation Successful") - case .Failure(let error): - print(error) - } + print(response.timeline) } ``` +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + ### Printable ```swift @@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled: ### Response Serialization +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples: + +```swift +public enum BackendError: ErrorType { + case Network(error: NSError) + case DataSerialization(reason: String) + case JSONSerialization(error: NSError) + case ObjectSerialization(reason: String) + case XMLSerialization(error: NSError) +} +``` + #### Creating a Custom Response Serializer Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. @@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/ ```swift extension Request { - public static func XMLResponseSerializer() -> ResponseSerializer { + public static func XMLResponseSerializer() -> ResponseSerializer { return ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .Failure(.Network(error: error!)) } guard let validData = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil.")) } do { let XML = try ONOXMLDocument(data: validData) return .Success(XML) } catch { - return .Failure(error as NSError) + return .Failure(.XMLSerialization(error: error as NSError)) } } } - public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) } } @@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable { } extension Request { - public func responseObject(completionHandler: Response -> Void) -> Self { - let responseSerializer = ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) @@ -737,12 +783,10 @@ extension Request { { return .Success(responseObject) } else { - let failureReason = "JSON could not be serialized into response object: \(value)" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable { ```swift Alamofire.request(.GET, "https://example.com/users/mattt") - .responseObject { (response: Response) in + .responseObject { (response: Response) in debugPrint(response) } ``` @@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable { static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] } +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] { + var collection = [Self]() + + if let representation = representation as? [[String: AnyObject]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} + extension Alamofire.Request { - public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { - let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONSerializer.serializeResponse(request, response, data, error) @@ -790,12 +850,10 @@ extension Alamofire.Request { if let response = response { return .Success(T.collection(response: response, representation: value)) } else { - let failureReason = "Response collection could not be serialized due to nil response" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable { self.username = response.URL!.lastPathComponent! self.name = representation.valueForKeyPath("name") as! String } - - static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { - var users: [User] = [] - - if let representation = representation as? [[String: AnyObject]] { - for userRepresentation in representation { - if let user = User(response: response, representation: userRepresentation) { - users.append(user) - } - } - } - - return users - } } ``` ```swift Alamofire.request(.GET, "http://example.com/users") - .responseCollection { (response: Response<[User], NSError>) in + .responseCollection { (response: Response<[User], BackendError>) in debugPrint(response) } ``` @@ -912,7 +956,7 @@ enum Router: URLRequestConvertible { var URLRequest: NSMutableURLRequest { let result: (path: String, parameters: [String: AnyObject]) = { switch self { - case .Search(let query, let page) where page > 1: + case .Search(let query, let page) where page > 0: return ("/search", ["q": query, "offset": Router.perPage * page]) case .Search(let query, _): return ("/search", ["q": query]) @@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible { Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt ``` +### SessionDelegate + +By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. +public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + +/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. +public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + +/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. +public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + +/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. +public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let delegate: Alamofire.Manager.SessionDelegate = manager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: Manager.SessionDelegate { + override func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.URLSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + ### Security Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. @@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server #### Validating the Certificate Chain -Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. @@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends > It is recommended to always use valid certificates in production environments. ---- +### Network Reachability -## Component Libraries +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") -* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +* **Do NOT** use Reachability to determine if a network request should be sent. + * You should **ALWAYS** send it. +* When Reachability is restored, use the event to retry failed network requests. + * Even though the network requests may still fail, this is a good moment to retry them. +* The network reachability status can be useful for determining why a network request may have failed. + * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- ## Open Rdars The following rdars have some affect on the current implementation of Alamofire. * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage ## FAQ @@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http:// If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +* Pay our legal fees to register as a federal non-profit organization +* Pay our yearly legal fees to keep the non-profit in good status +* Pay for our mail servers to help us stay on top of all questions and security issues +* Potentially fund test servers to make it easier for us to test the edge cases +* Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + ## License Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift index b866f42264f..0945204dcca 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -1,31 +1,33 @@ -// Alamofire.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Alamofire.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation // MARK: - URLStringConvertible /** - Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to + Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { @@ -42,27 +44,19 @@ public protocol URLStringConvertible { } extension String: URLStringConvertible { - public var URLString: String { - return self - } + public var URLString: String { return self } } extension NSURL: URLStringConvertible { - public var URLString: String { - return absoluteString - } + public var URLString: String { return absoluteString } } extension NSURLComponents: URLStringConvertible { - public var URLString: String { - return URL!.URLString - } + public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { - public var URLString: String { - return URL!.URLString - } + public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible @@ -76,9 +70,7 @@ public protocol URLRequestConvertible { } extension NSURLRequest: URLRequestConvertible { - public var URLRequest: NSMutableURLRequest { - return self.mutableCopy() as! NSMutableURLRequest - } + public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } // MARK: - Convenience @@ -89,7 +81,16 @@ func URLRequest( headers: [String: String]? = nil) -> NSMutableURLRequest { - let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) + let mutableURLRequest: NSMutableURLRequest + + if let request = URLString as? NSMutableURLRequest { + mutableURLRequest = request + } else if let request = URLString as? NSURLRequest { + mutableURLRequest = request.URLRequest + } else { + mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) + } + mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { @@ -353,11 +354,11 @@ public func download(URLRequest: URLRequestConvertible, destination: Request.Dow // MARK: Resume Data /** - Creates a request using the shared manager instance for downloading from the resume data produced from a + Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` - when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift index b9a043cb8e3..52e90badfde 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -1,24 +1,26 @@ -// Download.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Download.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -112,8 +114,8 @@ extension Manager { If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` - when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. @@ -128,14 +130,14 @@ extension Manager { extension Request { /** - A closure executed once a request has successfully completed in order to determine where to move the temporary - file written to during the download process. The closure takes two arguments: the temporary file URL and the URL + A closure executed once a request has successfully completed in order to determine where to move the temporary + file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved. */ public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL /** - Creates a download file destination closure which uses the default file manager to move the temporary file to a + Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask. - parameter directory: The search path directory. `.DocumentDirectory` by default. @@ -211,12 +213,14 @@ extension Request { totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, downloadTask, bytesWritten, - totalBytesWritten, + totalBytesWritten, totalBytesExpectedToWrite ) } else { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift index 7a813f1b813..467d99c916c 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -1,24 +1,26 @@ -// Error.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Error.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -39,6 +41,15 @@ public struct Error { case PropertyListSerializationFailed = -6007 } + /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. + public struct UserInfoKeys { + /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. + public static let ContentType = "ContentType" + + /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. + public static let StatusCode = "StatusCode" + } + /** Creates an `NSError` with the given error code and failure reason. @@ -47,6 +58,7 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } @@ -59,8 +71,18 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } + + static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { + return error(domain: domain, code: code.rawValue, failureReason: failureReason) + } + + static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: domain, code: code, userInfo: userInfo) + } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift index d81c7380fa8..cbfb5c77bff 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -1,24 +1,26 @@ -// Manager.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Manager.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -30,7 +32,7 @@ public class Manager { // MARK: - Properties /** - A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly + A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests. */ public static let sharedInstance: Manager = { @@ -56,17 +58,41 @@ public class Manager { // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { - let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" - let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" - let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" - let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString - let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + let osNameVersion: String = { + let versionString: String - if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { - return mutableUserAgent as String - } + if #available(OSX 10.10, *) { + let version = NSProcessInfo.processInfo().operatingSystemVersion + versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + } else { + versionString = "10.9" + } + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(OSX) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))" } return "Alamofire" @@ -91,14 +117,14 @@ public class Manager { public var startRequestsImmediately: Bool = true /** - The background completion handler closure provided by the UIApplicationDelegate - `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background - completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + The background completion handler closure provided by the UIApplicationDelegate + `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. - - If you need to handle your own events before the handler is called, then you need to override the + + If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. - + `nil` by default. */ public var backgroundCompletionHandler: (() -> Void)? @@ -108,11 +134,11 @@ public class Manager { /** Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. - - parameter configuration: The configuration used to construct the managed session. + - parameter configuration: The configuration used to construct the managed session. `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by default. - - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance. @@ -143,11 +169,11 @@ public class Manager { delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { + guard delegate === session.delegate else { return nil } + self.delegate = delegate self.session = session - guard delegate === session.delegate else { return nil } - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } @@ -218,18 +244,18 @@ public class Manager { /** Responsible for handling all delegate callbacks for the underlying session. */ - public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) - subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + /// Access the task delegate for the specified task in a thread-safe manner. + public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } - set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } @@ -254,6 +280,9 @@ public class Manager { /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. + public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? @@ -281,6 +310,11 @@ public class Manager { didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? @@ -321,11 +355,23 @@ public class Manager { /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. - public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and + /// requires the caller to call the `completionHandler`. + public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? @@ -342,8 +388,8 @@ public class Manager { - parameter task: The task whose request resulted in a redirect. - parameter response: An object containing the server’s response to the original request. - parameter request: A URL request object filled out with the new location. - - parameter completionHandler: A closure that your handler should call with either the value of the request - parameter, a modified URL request object, or NULL to refuse the redirect and + - parameter completionHandler: A closure that your handler should call with either the value of the request + parameter, a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response. */ public func URLSession( @@ -351,8 +397,13 @@ public class Manager { task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, - completionHandler: ((NSURLRequest?) -> Void)) + completionHandler: NSURLRequest? -> Void) { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { @@ -374,10 +425,16 @@ public class Manager { session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + if let taskDidReceiveChallenge = taskDidReceiveChallenge { - completionHandler(taskDidReceiveChallenge(session, task, challenge)) + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.URLSession( session, @@ -400,8 +457,13 @@ public class Manager { public func URLSession( session: NSURLSession, task: NSURLSessionTask, - needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + needNewBodyStream completionHandler: NSInputStream? -> Void) { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { @@ -452,6 +514,8 @@ public class Manager { delegate.URLSession(session, task: task, didCompleteWithError: error) } + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) + self[task] = nil } @@ -462,6 +526,10 @@ public class Manager { /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? @@ -469,7 +537,11 @@ public class Manager { public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. - public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? // MARK: Delegate Methods @@ -479,16 +551,21 @@ public class Manager { - parameter session: The session containing the data task that received an initial reply. - parameter dataTask: The data task that received an initial reply. - parameter response: A URL response object populated with headers. - - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a - constant to indicate whether the transfer should continue as a data task or + - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + constant to indicate whether the transfer should continue as a data task or should become a download task. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, - completionHandler: ((NSURLSessionResponseDisposition) -> Void)) + completionHandler: NSURLSessionResponseDisposition -> Void) { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { @@ -538,20 +615,25 @@ public class Manager { - parameter session: The session containing the data (or upload) task. - parameter dataTask: The data (or upload) task. - - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current - caching policy and the values of certain received headers, such as the Pragma + - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + caching policy and the values of certain received headers, such as the Pragma and Cache-Control headers. - - parameter completionHandler: A block that your handler must call, providing either the original proposed - response, a modified version of that response, or NULL to prevent caching the - response. If your delegate implements this method, it must call this completion + - parameter completionHandler: A block that your handler must call, providing either the original proposed + response, a modified version of that response, or NULL to prevent caching the + response. If your delegate implements this method, it must call this completion handler; otherwise, your app leaks memory. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, - completionHandler: ((NSCachedURLResponse?) -> Void)) + completionHandler: NSCachedURLResponse? -> Void) { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { @@ -586,8 +668,8 @@ public class Manager { - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that finished. - - parameter location: A file URL for the temporary file. Because the file is temporary, you must either - open the file for reading or move it to a permanent location in your app’s sandbox + - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method. */ public func URLSession( @@ -607,11 +689,11 @@ public class Manager { - parameter session: The session containing the download task. - parameter downloadTask: The download task. - - parameter bytesWritten: The number of bytes transferred since the last time this delegate + - parameter bytesWritten: The number of bytes transferred since the last time this delegate method was called. - parameter totalBytesWritten: The total number of bytes transferred so far. - - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length - header. If this header was not provided, the value is + - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + header. If this header was not provided, the value is `NSURLSessionTransferSizeUnknown`. */ public func URLSession( @@ -639,11 +721,11 @@ public class Manager { - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that resumed. See explanation in the discussion. - - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the - existing content, then this value is zero. Otherwise, this value is an - integer representing the number of bytes on disk that do not need to be + - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + existing content, then this value is zero. Otherwise, this value is an + integer representing the number of bytes on disk that do not need to be retrieved again. - - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is NSURLSessionTransferSizeUnknown. */ public func URLSession( @@ -674,17 +756,21 @@ public class Manager { // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { + #if !os(OSX) + if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + switch selector { - case "URLSession:didBecomeInvalidWithError:": + case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil - case "URLSession:didReceiveChallenge:completionHandler:": - return sessionDidReceiveChallenge != nil - case "URLSessionDidFinishEventsForBackgroundURLSession:": - return sessionDidFinishEventsForBackgroundURLSession != nil - case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": - return taskWillPerformHTTPRedirection != nil - case "URLSession:dataTask:didReceiveResponse:completionHandler:": - return dataTaskDidReceiveResponse != nil + case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespondToSelector(selector) } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift index 8c37f164e7e..5a7ef09c82e 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -1,24 +1,26 @@ -// MultipartFormData.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// MultipartFormData.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -29,10 +31,10 @@ import CoreServices #endif /** - Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode - multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead - to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the - data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for + Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode + multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead + to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the + data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well @@ -116,7 +118,7 @@ public class MultipartFormData { self.bodyParts = [] /** - * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more * information, please refer to the following article: * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html */ @@ -217,7 +219,7 @@ public class MultipartFormData { appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" - setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) } } @@ -245,8 +247,7 @@ public class MultipartFormData { guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -261,8 +262,7 @@ public class MultipartFormData { } guard isReachable else { - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") return } @@ -277,8 +277,7 @@ public class MultipartFormData { where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -301,8 +300,7 @@ public class MultipartFormData { guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -312,8 +310,7 @@ public class MultipartFormData { guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) return } @@ -370,8 +367,8 @@ public class MultipartFormData { /** Encodes all the appended body parts into a single `NSData` object. - It is important to note that this method will load all the appended body parts into memory all at the same - time. This method should only be used when the encoded data will have a small memory footprint. For large data + It is important to note that this method will load all the appended body parts into memory all at the same + time. This method should only be used when the encoded data will have a small memory footprint. For large data cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - throws: An `NSError` if encoding encounters an error. @@ -413,10 +410,10 @@ public class MultipartFormData { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream @@ -425,10 +422,9 @@ public class MultipartFormData { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) } - outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true @@ -439,7 +435,6 @@ public class MultipartFormData { } outputStream.close() - outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } // MARK: - Private - Body Part Encoding @@ -476,7 +471,6 @@ public class MultipartFormData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? @@ -495,7 +489,7 @@ public class MultipartFormData { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) break } else { break @@ -503,7 +497,6 @@ public class MultipartFormData { } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { throw error @@ -537,7 +530,6 @@ public class MultipartFormData { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { @@ -556,14 +548,13 @@ public class MultipartFormData { try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } private func writeFinalBoundaryDataForBodyPart( @@ -598,7 +589,7 @@ public class MultipartFormData { if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" - throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten @@ -661,9 +652,8 @@ public class MultipartFormData { // MARK: - Private - Errors - private func setBodyPartError(error: NSError) { - if bodyPartError == nil { - bodyPartError = error - } + private func setBodyPartError(code code: Int, failureReason: String) { + guard bodyPartError == nil else { return } + bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 00000000000..d5e00ae7005 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,244 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/** + The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and + WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to retry + network requests when a connection is established. It should not be used to prevent a user from initiating a network + request, as it's possible that an initial request may be required to establish reachability. +*/ +public class NetworkReachabilityManager { + /** + Defines the various states of network reachability. + + - Unknown: It is unknown whether the network is reachable. + - NotReachable: The network is not reachable. + - ReachableOnWWAN: The network is reachable over the WWAN connection. + - ReachableOnWiFi: The network is reachable over the WiFi connection. + */ + public enum NetworkReachabilityStatus { + case Unknown + case NotReachable + case Reachable(ConnectionType) + } + + /** + Defines the various connection types detected by reachability flags. + + - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. + - WWAN: The connection type is a WWAN connection. + */ + public enum ConnectionType { + case EthernetOrWiFi + case WWAN + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = NetworkReachabilityStatus -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .Unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /** + Creates a `NetworkReachabilityManager` instance with the specified host. + + - parameter host: The host used to evaluate network reachability. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /** + Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + + Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + status of the device, both IPv4 and IPv6. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(sizeofValue(address)) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(&address, { + SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /** + Starts listening for changes in network reachability status. + + - returns: `true` if listening was started successfully, `false` otherwise. + */ + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + dispatch_async(listenerQueue) { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /** + Stops listening for changes in network reachability status. + */ + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.Reachable) else { return .NotReachable } + + var networkStatus: NetworkReachabilityStatus = .NotReachable + + if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + + if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { + if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + } + + #if os(iOS) + if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } + #endif + + return networkStatus + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/** + Returns whether the two network reachability status values are equal. + + - parameter lhs: The left-hand side value to compare. + - parameter rhs: The right-hand side value to compare. + + - returns: `true` if the two values are equal, `false` otherwise. +*/ +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.Unknown, .Unknown): + return true + case (.NotReachable, .NotReachable): + return true + case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 00000000000..a7dbcfeffaa --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,47 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. +public struct Notifications { + /// Used as a namespace for all `NSURLSessionTask` related notifications. + public struct Task { + /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed + /// `NSURLSessionTask`. + public static let DidResume = "com.alamofire.notifications.task.didResume" + + /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the + /// suspended `NSURLSessionTask`. + public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" + + /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the + /// cancelled `NSURLSessionTask`. + public static let DidCancel = "com.alamofire.notifications.task.didCancel" + + /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the + /// completed `NSURLSessionTask`. + public static let DidComplete = "com.alamofire.notifications.task.didComplete" + } +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift index d56d2d6c3a7..c54e58b32d6 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -1,24 +1,26 @@ -// ParameterEncoding.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ParameterEncoding.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -36,8 +38,8 @@ public enum Method: String { /** Used to specify the way in which a set of parameters are applied to a URL request. - - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, - and `DELETE` requests, or set as the body for requests with any other HTTP method. The + - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, + and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array @@ -47,8 +49,8 @@ public enum Method: String { - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is - set as the body of the request. The `Content-Type` HTTP header field of an encoded request is + - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is + set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, @@ -69,10 +71,10 @@ public enum ParameterEncoding { /** Creates a URL request by encoding parameters and applying them onto an existing request. - - parameter URLRequest: The request to have parameters applied - - parameter parameters: The parameters to apply + - parameter URLRequest: The request to have parameters applied. + - parameter parameters: The parameters to apply. - - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, + - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( @@ -82,9 +84,7 @@ public enum ParameterEncoding { { var mutableURLRequest = URLRequest.URLRequest - guard let parameters = parameters where !parameters.isEmpty else { - return (mutableURLRequest, nil) - } + guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil @@ -118,7 +118,10 @@ public enum ParameterEncoding { } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { - if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { + if let + URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) + where !parameters.isEmpty + { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL @@ -141,7 +144,10 @@ public enum ParameterEncoding { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) - mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -153,7 +159,11 @@ public enum ParameterEncoding { format: format, options: options ) - mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -219,7 +229,7 @@ public enum ParameterEncoding { //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // @@ -236,7 +246,7 @@ public enum ParameterEncoding { while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) - let range = Range(start: startIndex, end: endIndex) + let range = startIndex.. [String: String] { + guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } + + let credential = data.base64EncodedStringWithOptions([]) + + return ["Authorization": "Basic \(credential)"] + } + // MARK: - Progress /** - Sets a closure to be called periodically during the lifecycle of the request as data is written to or read + Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server. - - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected + - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write. - - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes + - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes expected to read. - parameter closure: The code to be executed periodically during the lifecycle of the request. @@ -130,8 +153,8 @@ public class Request { /** Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. - This closure returns the bytes most recently received from the server, not including data from previous calls. - If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + This closure returns the bytes most recently received from the server, not including data from previous calls. + If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is also important to note that the `response` closure will be called with nil `responseData`. - parameter closure: The code to be executed periodically during the lifecycle of the request. @@ -149,17 +172,21 @@ public class Request { // MARK: - State /** - Suspends the request. + Resumes the request. */ - public func suspend() { - task.suspend() + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) } /** - Resumes the request. + Suspends the request. */ - public func resume() { - task.resume() + public func suspend() { + task.suspend() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) } /** @@ -176,12 +203,14 @@ public class Request { } else { task.cancel() } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) } // MARK: - TaskDelegate /** - The task delegate is responsible for handling all delegate callbacks for the underlying task as well as + The task delegate is responsible for handling all delegate callbacks for the underlying task as well as executing all operations attached to the serial operation queue upon task completion. */ public class TaskDelegate: NSObject { @@ -195,6 +224,7 @@ public class Request { var data: NSData? { return nil } var error: NSError? + var initialResponseTime: CFAbsoluteTime? var credential: NSURLCredential? init(task: NSURLSessionTask) { @@ -272,7 +302,7 @@ public class Request { } } else { if challenge.previousFailureCount > 0 { - disposition = .CancelAuthenticationChallenge + disposition = .RejectProtectionSpace } else { credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) @@ -381,6 +411,8 @@ public class Request { } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { @@ -426,7 +458,7 @@ public class Request { extension Request: CustomStringConvertible { /** - The textual representation used when written to an output stream, which includes the HTTP method and URL, as + The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received. */ public var description: String { @@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible { let protectionSpace = NSURLProtectionSpace( host: host, port: URL.port?.integerValue ?? 0, - `protocol`: URL.scheme, + protocol: URL.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) @@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible { } } - if let headerFields = request.allHTTPHeaderFields { - for (field, value) in headerFields { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + var headers: [NSObject: AnyObject] = [:] + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders where field != "Cookie" { + headers[field] = value } } - if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { - for (field, value) in additionalHeaders { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value } } + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + if let HTTPBodyData = request.HTTPBody, HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { - let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") + escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + components.append("-d \"\(escapedBody)\"") } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift index fa2fffb3dea..9c437ff6e41 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -1,24 +1,26 @@ -// Response.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Response.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -36,22 +38,33 @@ public struct Response { /// The result of response serialization. public let result: Result + /// The timeline of the complete lifecycle of the `Request`. + public let timeline: Timeline + /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. - + - parameter request: The URL request sent to the server. - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - + - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + - returns: the new `Response` instance. */ - public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) { + public init( + request: NSURLRequest?, + response: NSHTTPURLResponse?, + data: NSData?, + result: Result, + timeline: Timeline = Timeline()) + { self.request = request self.response = response self.data = data self.result = result + self.timeline = timeline } } @@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible { output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") return output.joinWithSeparator("\n") } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift index 4aaacf61e31..89e39544b8c 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -1,24 +1,26 @@ -// ResponseSerialization.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ResponseSerialization.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -29,10 +31,10 @@ import Foundation */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. - typealias SerializedObject + associatedtype SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. - typealias ErrorObject: ErrorType + associatedtype ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. @@ -99,7 +101,7 @@ extension Request { Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - - parameter responseSerializer: The response serializer responsible for serializing the request, response, + - parameter responseSerializer: The response serializer responsible for serializing the request, response, and data. - parameter completionHandler: The code to be executed once the request has finished. @@ -119,16 +121,25 @@ extension Request { self.delegate.error ) - dispatch_async(queue ?? dispatch_get_main_queue()) { - let response = Response( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result - ) + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime - completionHandler(response) - } + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: timeline + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } return self @@ -152,7 +163,7 @@ extension Request { guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -167,8 +178,12 @@ extension Request { - returns: The request. */ - public func responseData(completionHandler: Response -> Void) -> Self { - return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + public func responseData( + queue queue: dispatch_queue_t? = nil, + completionHandler: Response -> Void) + -> Self + { + return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } @@ -177,16 +192,16 @@ extension Request { extension Request { /** - Creates a response serializer that returns a string initialized from the response data with the specified + Creates a response serializer that returns a string initialized from the response data with the specified string encoding. - - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - returns: A string response serializer. */ public static func stringResponseSerializer( - var encoding encoding: NSStringEncoding? = nil) + encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer { return ResponseSerializer { _, response, data, error in @@ -196,23 +211,25 @@ extension Request { guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } - if let encodingName = response?.textEncodingName where encoding == nil { - encoding = CFStringConvertEncodingToNSStringEncoding( + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName where convertedEncoding == nil { + convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } - let actualEncoding = encoding ?? NSISOLatin1StringEncoding + let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } @@ -221,19 +238,21 @@ extension Request { /** Adds a handler to be called once the request has finished. - - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - server response, falling back to the default HTTP default character set, + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + server response, falling back to the default HTTP default character set, ISO-8859-1. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseString( - encoding encoding: NSStringEncoding? = nil, + queue queue: dispatch_queue_t? = nil, + encoding: NSStringEncoding? = nil, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) @@ -245,7 +264,7 @@ extension Request { extension Request { /** - Creates a response serializer that returns a JSON object constructed from the response data using + Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. @@ -263,7 +282,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -285,11 +304,13 @@ extension Request { - returns: The request. */ public func responseJSON( - options options: NSJSONReadingOptions = .AllowFragments, + queue queue: dispatch_queue_t? = nil, + options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) @@ -301,7 +322,7 @@ extension Request { extension Request { /** - Creates a response serializer that returns an object constructed from the response data using + Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options. - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. @@ -319,7 +340,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -337,17 +358,19 @@ extension Request { - parameter options: The property list reading options. `0` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 - arguments: the URL request, the URL response, the server data and the result + arguments: the URL request, the URL response, the server data and the result produced while creating the property list. - returns: The request. */ public func responsePropertyList( - options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + queue queue: dispatch_queue_t? = nil, + options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift index a8557cabb42..4aabf08bf8b 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -1,33 +1,35 @@ -// Result.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Result.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation /** Used to represent whether a request was successful or encountered an error. - - Success: The request and all post processing operations were successful resulting in the serialization of the + - Success: The request and all post processing operations were successful resulting in the serialization of the provided associated value. - - Failure: The request encountered an error resulting in a failure. The associated values are the original data + - Failure: The request encountered an error resulting in a failure. The associated values are the original data provided by the server as well as the error that caused the failure. */ public enum Result { @@ -73,7 +75,7 @@ public enum Result { // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a + /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { switch self { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift index 07cd848a606..7da516e8038 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -1,24 +1,26 @@ -// ServerTrustPolicy.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ServerTrustPolicy.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -30,9 +32,9 @@ public class ServerTrustPolicyManager { /** Initializes the `ServerTrustPolicyManager` instance with the given policies. - Since different servers and web services can have different leaf certificates, intermediate and even root - certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This - allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + Since different servers and web services can have different leaf certificates, intermediate and even root + certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key pinning for host3 and disabling evaluation for host4. - parameter policies: A dictionary of all policies mapped to a particular host. @@ -78,31 +80,31 @@ extension NSURLSession { // MARK: - ServerTrustPolicy /** - The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when - connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust + The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when + connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. - Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other - vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged + Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other + vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to - validate the host provided by the challenge. Applications are encouraged to always - validate the host in production environments to guarantee the validity of the server's + - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to + validate the host provided by the challenge. Applications are encouraged to always + validate the host in production environments to guarantee the validity of the server's certificate chain. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is - considered valid if one of the pinned certificates match one of the server certificates. - By validating both the certificate chain and host, certificate pinning provides a very - secure form of server trust validation mitigating most, if not all, MITM attacks. - Applications are encouraged to always validate the host and require a valid certificate + considered valid if one of the pinned certificates match one of the server certificates. + By validating both the certificate chain and host, certificate pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered - valid if one of the pinned public keys match one of the server certificate public keys. - By validating both the certificate chain and host, public key pinning provides a very - secure form of server trust validation mitigating most, if not all, MITM attacks. - Applications are encouraged to always validate the host and require a valid certificate + valid if one of the pinned public keys match one of the server certificate public keys. + By validating both the certificate chain and host, public key pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift index bc9ee450c5a..e463d9b2f81 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -1,30 +1,32 @@ -// Stream.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Stream.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation #if !os(watchOS) -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager { private enum Streamable { case Stream(String, Int) @@ -62,7 +64,7 @@ extension Manager { - parameter hostName: The hostname of the server to connect to. - parameter port: The port of the server to connect to. - :returns: The created stream request. + - returns: The created stream request. */ public func stream(hostName hostName: String, port: Int) -> Request { return stream(.Stream(hostName, port)) @@ -82,7 +84,7 @@ extension Manager { // MARK: - -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager.SessionDelegate: NSURLSessionStreamDelegate { // MARK: Override Closures diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 00000000000..f3477057987 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,138 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: NSTimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: NSTimeInterval + + /** + Creates a new `Timeline` instance with the specified request times. + + - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + Defaults to `0.0`. + - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + to `0.0`. + + - returns: The new `Timeline` instance. + */ + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift index ee6b34ced5b..21971e6e465 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -1,24 +1,26 @@ -// Upload.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Upload.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -192,12 +194,12 @@ extension Manager { public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 /** - Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as associated values. - - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with + - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with streaming information. - - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding error. */ public enum MultipartFormDataEncodingResult { @@ -208,17 +210,17 @@ extension Manager { /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. - It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. - The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. @@ -359,6 +361,8 @@ extension Request { totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift index 71d21e1afa6..b94e07d1e4e 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -1,24 +1,26 @@ -// Validation.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Validation.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -36,7 +38,7 @@ extension Request { } /** - A closure used to validate a request that takes a URL request and URL response, and returns whether the + A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid. */ public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult @@ -80,7 +82,17 @@ extension Request { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" - return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) + + let error = NSError( + domain: Error.Domain, + code: Error.Code.StatusCodeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.StatusCode: response.statusCode + ] + ) + + return .Failure(error) } } } @@ -128,7 +140,7 @@ extension Request { - returns: The request. */ - public func validate(contentType acceptableContentTypes: S) -> Self { + public func validate(contentType acceptableContentTypes: S) -> Self { return validate { _, response in guard let validData = self.delegate.data where validData.length > 0 else { return .Success } @@ -149,25 +161,38 @@ extension Request { } } + let contentType: String let failureReason: String if let responseContentType = response.MIMEType { + contentType = responseContentType + failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { + contentType = "" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } - return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) + let error = NSError( + domain: Error.Domain, + code: Error.Code.ContentTypeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.ContentType: contentType + ] + ) + + return .Failure(error) } } // MARK: - Automatic /** - Validates that the response has a status code in the default acceptable range of 200...299, and that the content + Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field. If validation fails, subsequent calls to response handlers will have an associated error. diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index 069b678d88c..4cdc0899bd5 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -9,14 +9,14 @@ "git": "git@github.com:swagger-api/swagger-mustache.git", "tag": "v1.0.0" }, + "authors": "", "license": "Apache License, Version 2.0", - "authors": "Apache License, Version 2.0", "homepage": "https://github.com/swagger-api/swagger-codegen", "summary": "PetstoreClient", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", "dependencies": { "Alamofire": [ - "~> 3.1.5" + "~> 3.4.1" ] } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock index b369a60a1bb..5dc0c9e1151 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock @@ -1,18 +1,18 @@ PODS: - - Alamofire (3.1.5) + - Alamofire (3.4.2) - PetstoreClient (0.0.1): - - Alamofire (~> 3.1.5) + - Alamofire (~> 3.4.1) DEPENDENCIES: - PetstoreClient (from `../`) EXTERNAL SOURCES: PetstoreClient: - :path: ../ + :path: "../" SPEC CHECKSUMS: - Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - PetstoreClient: 65dabd411c65d965d5b4c3d5decb909323d1363b + Alamofire: 6aa33201d20d069e1598891cf928883ff1888c7a + PetstoreClient: 7489b461499be1b2c4e0ed6624ca76c8db506297 PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index 98d247e012c..1b141de2352 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,46 +7,49 @@ objects = { /* Begin PBXBuildFile section */ - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */; }; - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */; }; - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */; }; 121BA006C3D23D9290D868AA19E4BFBA /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */; }; 1ED3811BA132299733D3A71543A4339C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; 2737DA3907C231E7CCCBF6075FCE4AB3 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */; }; + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */; }; 37D0F7B54F7677AEB499F204040C6DA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; 388FE86EB5084CB37EC19ED82DE8242C /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; 39EBC7781F42F6F790D3E54F3E8D8ED1 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; 3CA0C61EB5AA01268C12B7E61FF59C56 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */; }; + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */; }; 40AED0FDEFFB776F649058C34D72BB95 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; 45961D28C6B8E4BAB87690F714B8727B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */; }; 562F951C949B9293B74C2E5D86BEF1BC /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; 59C731A013A3F62794AABFB1C1025B4F /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */; }; + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */; }; + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */; }; + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */; }; 7D0C7E08FEC92B9C59B3EAFB8D15026D /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */; }; 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */; }; - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */; }; 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */; }; 909E1A21FF97D3DFD0E2707B0E078686 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; 93A9E4EBCD41B6C350DB55CB545D797E /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */; }; - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */; }; - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */; }; + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */; }; + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */; }; + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */; }; + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */; }; + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */; }; C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779B19103BE8402A434ED95F67573911 /* Validation.swift */; }; + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */; }; C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; CA8020EE393C1F6085F284A7CAE3B9E3 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */; }; D228AFA3B6BFAE551ADA6A57A57F8DF9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */; }; DAF614ED4A24537ACAF1F517EF31668E /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */; }; F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */; }; - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -61,14 +64,14 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; /* End PBXContainerItemProxy section */ @@ -76,15 +79,17 @@ /* Begin PBXFileReference section */ 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; - 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; - 21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -92,53 +97,54 @@ 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; - 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 5175E677ADC3F810A4FB10B104C4332B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; - 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - 5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 5C5763A83A1E028B6C4A073221CB764F /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 779B19103BE8402A434ED95F67573911 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 8FFF564423DBE209836D47626963E9D4 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; - ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; - C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; - E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; - F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; /* End PBXFileReference section */ @@ -151,11 +157,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -179,28 +185,6 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */ = { - isa = PBXGroup; - children = ( - 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */, - ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */, - 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */, - 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */, - 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */, - 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */, - FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */, - 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */, - F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */, - 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */, - 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */, - C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */, - 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */, - 779B19103BE8402A434ED95F67573911 /* Validation.swift */, - 405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */, - ); - path = Alamofire; - sourceTree = ""; - }; 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { isa = PBXGroup; children = ( @@ -213,14 +197,6 @@ path = Models; sourceTree = ""; }; - 20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */ = { - isa = PBXGroup; - children = ( - 09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */, - ); - name = Pods; - sourceTree = ""; - }; 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { isa = PBXGroup; children = ( @@ -237,18 +213,12 @@ name = iOS; sourceTree = ""; }; - 405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */ = { + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = { isa = PBXGroup; children = ( - 21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */, - 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */, - 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */, - E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */, - 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */, - 5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */, + 6E519FC8760483F5D136181B2EBCBDEB /* Alamofire */, ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; + name = Pods; sourceTree = ""; }; 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { @@ -260,13 +230,52 @@ name = Frameworks; sourceTree = ""; }; + 68F6D4CBC8B6CDE1D634D9F379F37168 /* Support Files */ = { + isa = PBXGroup; + children = ( + 5C5763A83A1E028B6C4A073221CB764F /* Alamofire.modulemap */, + A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */, + 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */, + 8FFF564423DBE209836D47626963E9D4 /* Alamofire-prefix.pch */, + AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */, + 5175E677ADC3F810A4FB10B104C4332B /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 6E519FC8760483F5D136181B2EBCBDEB /* Alamofire */ = { + isa = PBXGroup; + children = ( + 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */, + 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */, + 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */, + 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */, + 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */, + F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */, + 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */, + AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */, + 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */, + DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */, + 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */, + 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */, + 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */, + F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */, + 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */, + 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */, + 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */, + 68F6D4CBC8B6CDE1D634D9F379F37168 /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, 59B91F212518421F271EBA85D5530651 /* Frameworks */, - 20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */, + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */, 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */, C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, ); @@ -395,27 +404,27 @@ /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { + 6C794A7763C2F85750D66CDD002E271F /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, + A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 6C794A7763C2F85750D66CDD002E271F /* Headers */ = { + 8EB9FB8BCBCBC01234ED5877A870758B /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */, + 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 8EB9FB8BCBCBC01234ED5877A870758B /* Headers */ = { + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */, + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -449,23 +458,6 @@ productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */; productType = "com.apple.product-type.framework"; }; - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { - isa = PBXNativeTarget; - buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */; - buildPhases = ( - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */, - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */, - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Alamofire; - productName = Alamofire; - productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { isa = PBXNativeTarget; buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; @@ -501,6 +493,23 @@ productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; productType = "com.apple.product-type.framework"; }; + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -522,7 +531,7 @@ projectDirPath = ""; projectRoot = ""; targets = ( - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, 757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */, 01C67FBB627BDC9D36B9F648C0BF5228 /* Pods-SwaggerClient */, 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, @@ -560,33 +569,36 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */, + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { + C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */, - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */, - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */, - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */, - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */, - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */, - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */, - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */, - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */, - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */, - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */, - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */, - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */, - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */, - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */, + C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -596,13 +608,13 @@ 9D7C00D5DABDA9EE2ED06BE7F85DD5EA /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */; }; A2B064722D89556FD34AF0A4A3EC3847 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 815A2A76D6EC0B2933867EA1BA7E51D8 /* PBXContainerItemProxy */; }; A51999658423B0F25DD2B4FEECD542E3 /* PBXTargetDependency */ = { @@ -614,6 +626,35 @@ /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; 51E864C21FD4E8BF48B7DE196DE05017 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; @@ -648,6 +689,36 @@ }; name = Debug; }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; 7C4A68800C97518F39692FF062F013EE /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; @@ -785,35 +856,6 @@ }; name = Release; }; - 9B26D3A39011247999C097562A550399 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; B316166B7E92675830371A4D5A9C5B6B /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; @@ -844,36 +886,6 @@ }; name = Debug; }; - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; F594C655D48020EC34B00AA63E001773 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { @@ -966,20 +978,20 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - B316166B7E92675830371A4D5A9C5B6B /* Debug */, - 95F68EBF32996F2AC8422FE5C210682D /* Release */, + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, - 9B26D3A39011247999C097562A550399 /* Release */, + B316166B7E92675830371A4D5A9C5B6B /* Debug */, + 95F68EBF32996F2AC8422FE5C210682D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist index c1aea25c248..152c333e441 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.5 + 3.4.2 CFBundleSignature ???? CFBundleVersion diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown index 3852291ae7d..938fc5f29a8 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## Alamofire -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist index c188b147b3b..289edb2592c 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 3d557a9280f..7cbaf74825f 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -143,12 +143,16 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, + A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */, + CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */, + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */, + 3D9471620628F03313096EB2 /* 📦 Embed Pods Frameworks */, + EEEC2B2D0497D38CEAD2DB24 /* 📦 Copy Pods Resources */, ); buildRules = ( ); @@ -163,12 +167,16 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, + FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */, + B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */, + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */, + ECE47F6BF90C3848F6E94AFF /* 📦 Embed Pods Frameworks */, + 1494090872F3F18E536E8902 /* 📦 Copy Pods Resources */, ); buildRules = ( ); @@ -239,7 +247,7 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { + 1494090872F3F18E536E8902 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -254,14 +262,29 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -269,7 +292,7 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { + 3D9471620628F03313096EB2 /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -284,14 +307,29 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -299,7 +337,37 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -314,7 +382,52 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { + B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + ECE47F6BF90C3848F6E94AFF /* 📦 Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + EEEC2B2D0497D38CEAD2DB24 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -329,6 +442,21 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; showEnvVarsInLog = 0; }; + FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index 3d3ca03392a..7446c53aa3b 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -72,16 +72,11 @@ class PetAPITests: XCTestCase { let expectation = self.expectationWithDescription("testDeletePet") PetAPI.deletePet(petId: 1000) { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard error == nil else { XCTFail("error deleting pet") return } - + expectation.fulfill() } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 68232d063d1..ba235ca32db 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -11,34 +11,27 @@ import XCTest @testable import SwaggerClient class StoreAPITests: XCTestCase { + + let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" let testTimeout = 10.0 - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - func test1PlaceOrder() { let expectation = self.expectationWithDescription("testPlaceOrder") + let shipDate = NSDate() let newOrder = Order() newOrder.id = 1000 newOrder.petId = 1000 newOrder.complete = false newOrder.quantity = 10 - newOrder.shipDate = NSDate() + newOrder.shipDate = shipDate // use explicit naming to reference the enum so that we test we don't regress on enum naming newOrder.status = Order.Status.Placed StoreAPI.placeOrder(body: newOrder) { (order, error) in guard error == nil else { - XCTFail("error placing order") + XCTFail("error placing order: \(error.debugDescription)") return } @@ -46,6 +39,8 @@ class StoreAPITests: XCTestCase { XCTAssert(order.id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .Placed, "invalid status") + XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), + "Date should be idempotent") expectation.fulfill() } @@ -59,7 +54,7 @@ class StoreAPITests: XCTestCase { StoreAPI.getOrderById(orderId: "1000") { (order, error) in guard error == nil else { - XCTFail("error retrieving order") + XCTFail("error retrieving order: \(error.debugDescription)") return } @@ -79,20 +74,49 @@ class StoreAPITests: XCTestCase { let expectation = self.expectationWithDescription("testDeleteOrder") StoreAPI.deleteOrder(orderId: "1000") { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard error == nil else { XCTFail("error deleting order") return } - + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } + func testDownloadProgress() { + let responseExpectation = self.expectationWithDescription("obtain response") + let progressExpectation = self.expectationWithDescription("obtain progress") + let requestBuilder = StoreAPI.getOrderByIdWithRequestBuilder(orderId: "1000") + + requestBuilder.onProgressReady = { (progress) in + progressExpectation.fulfill() + } + + requestBuilder.execute { (response, error) in + responseExpectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + +} + +private extension NSDate { + + /** + Returns true if the dates are equal given the format string. + + - parameter date: The date to compare to. + - parameter format: The format string to use to compare. + + - returns: true if the dates are equal, given the format string. + */ + func isEqual(date: NSDate, format: String) -> Bool { + let fmt = NSDateFormatter() + fmt.dateFormat = format + return fmt.stringFromDate(self).isEqual(fmt.stringFromDate(date)) + } + } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 213e69c56fe..0bd94f524b6 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -28,15 +28,11 @@ class UserAPITests: XCTestCase { let expectation = self.expectationWithDescription("testLogin") UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in - // The server isn't returning JSON - and currently the alamofire implementation - // always parses responses as JSON, so making an exception for this here - // Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." - // UserInfo={NSDebugDescription=Invalid value around character 0.} - guard let error = error where error._code == 3840 else { + guard error == nil else { XCTFail("error logging in") return } - + expectation.fulfill() } @@ -47,16 +43,11 @@ class UserAPITests: XCTestCase { let expectation = self.expectationWithDescription("testLogout") UserAPI.logoutUser { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard error == nil else { XCTFail("error logging out") return } - + expectation.fulfill() } @@ -77,16 +68,11 @@ class UserAPITests: XCTestCase { newUser.userStatus = 0 UserAPI.createUser(body: newUser) { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard error == nil else { XCTFail("error creating user") return } - + expectation.fulfill() } @@ -121,16 +107,11 @@ class UserAPITests: XCTestCase { let expectation = self.expectationWithDescription("testDeleteUser") UserAPI.deleteUser(username: "test@test.com") { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard error == nil else { XCTFail("error deleting user") return } - + expectation.fulfill() } diff --git a/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore +++ b/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient.podspec b/samples/client/petstore/swift/promisekit/PetstoreClient.podspec index b4eccbce888..25ab9199796 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient.podspec +++ b/samples/client/petstore/swift/promisekit/PetstoreClient.podspec @@ -4,11 +4,11 @@ Pod::Spec.new do |s| s.osx.deployment_target = '10.9' s.version = '0.0.1' s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } - s.authors = + s.authors = '' s.license = 'Apache License, Version 2.0' s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 3.1.1' - s.dependency 'Alamofire', '~> 3.1.5' + s.dependency 'Alamofire', '~> 3.4.1' end diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift index 96eead0d8dd..ab0ea147e4f 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -37,6 +37,9 @@ public class RequestBuilder { let method: String let URLString: String + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index c7e5a6402b5..8388537a83e 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -156,17 +156,17 @@ public class PetAPI: APIBase { /** Finds Pets by status - GET /pet/findByStatus - - Multiple status values can be provided with comma seperated strings + - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -222,24 +222,24 @@ public class PetAPI: APIBase { /** Finds Pets by tags - GET /pet/findByTags - - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -248,21 +248,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -271,7 +271,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -328,26 +328,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -356,21 +356,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -379,7 +379,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 8736f9ee2e0..ab072c821f8 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -101,12 +101,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int32]> */ @@ -159,36 +159,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -244,36 +244,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 1b5ada9da67..98afec0c80a 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -253,16 +253,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -271,17 +271,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -290,7 +290,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -348,8 +348,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2faa0a6f24d..4ea47d8926c 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -12,8 +12,33 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { } } +public struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = dispatch_queue_create("SynchronizedDictionary", DISPATCH_QUEUE_CONCURRENT) + + public subscript(key: K) -> V? { + get { + var value: V? + + dispatch_sync(queue) { + value = self.dictionary[key] + } + + return value + } + + set { + dispatch_barrier_sync(queue) { + self.dictionary[key] = newValue + } + } + } + +} + // Store manager to retain its reference -private var managerStore: [String: Alamofire.Manager] = [:] +private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { @@ -57,15 +82,22 @@ class AlamofireRequestBuilder: RequestBuilder { encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: { encodingResult in switch encodingResult { - case .Success(let upload, _, _): - self.processRequest(upload, managerId, completion) + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): - completion(response: nil, error: encodingError) + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) } } ) } else { - processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) } } @@ -75,30 +107,99 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.validate().responseJSON(options: .AllowFragments) { response in - managerStore.removeValueForKey(managerId) + let cleanupRequest = { + managerStore[managerId] = nil + } - if response.result.isFailure { - completion(response: nil, error: response.result.error) - return - } + let validatedRequest = request.validate() - if () is T { - completion(response: Response(response: response.response!, body: () as! T), error: nil) - return - } - if let json: AnyObject = response.result.value { - let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), error: nil) - return - } else if "" is T { - // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release - // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), error: nil) - return - } + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) + case is NSData.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) + } } } diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift index 62d374eed05..976ff5a7c3b 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -59,11 +59,17 @@ extension Dictionary: JSONEncodable { } } +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} private let dateFormatter: NSDateFormatter = { - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt }() extension NSDate: JSONEncodable { @@ -72,6 +78,12 @@ extension NSDate: JSONEncodable { } } +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + extension RequestBuilder { public func execute() -> Promise> { let deferred = Promise>.pendingPromise() diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index cad60a236a7..32175b605a3 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -10,18 +10,22 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + public class Response { public let statusCode: Int public let header: [String: String] - public let body: T + public let body: T? - public init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T?) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { @@ -62,9 +66,15 @@ class Decoders { if T.self is Int64.Type && source is NSNumber { return source.longLongValue as! T; } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } if source is T { return source as! T } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } let key = "\(T.self)" if let decoder = decoders[key] { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE index bf300e4482e..4cfbf72a4d8 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md index bcc0ff4bd05..cce2041d9d9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md @@ -1,7 +1,7 @@ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) -[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) @@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift. - [x] Comprehensive Unit Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. + ## Requirements - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 7.2+ +- Xcode 7.3+ ## Migration Guides @@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo ```ruby source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '8.0' +platform :ios, '9.0' use_frameworks! -pod 'Alamofire', '~> 3.0' +target '' do + pod 'Alamofire', '~> 3.4' +end ``` Then, run the following command: @@ -86,7 +95,7 @@ $ brew install carthage To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl -github "Alamofire/Alamofire" ~> 3.0 +github "Alamofire/Alamofire" ~> 3.4 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. @@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) > Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + ### Response Serialization **Built-in Response Methods** @@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .response { request, response, data, error in print(request) print(response) @@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) } ``` -> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. #### Response Data Handler ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .responseData { response in print(response.request) print(response.response) @@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") @@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get") ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseJSON { response in debugPrint(response) } @@ -221,6 +266,7 @@ Response handlers can even be chained: ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Response String: \(response.result.value)") } @@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global ` ```swift let headers = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", - "Content-Type": "application/x-www-form-urlencoded" + "Accept": "application/json" ] Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) @@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) print("Total bytes written on main queue: \(totalBytesWritten)") } } + .validate() .responseJSON { response in debugPrint(response) } @@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") } ``` -### Validation - -By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. - -#### Manual Validation - -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { response in - print(response) - } -``` - -#### Automatic Validation +### Timeline -Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .responseJSON { response in - switch response.result { - case .Success: - print("Validation Successful") - case .Failure(let error): - print(error) - } + print(response.timeline) } ``` +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + ### Printable ```swift @@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled: ### Response Serialization +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples: + +```swift +enum BackendError: ErrorType { + case Network(error: NSError) + case DataSerialization(reason: String) + case JSONSerialization(error: NSError) + case ObjectSerialization(reason: String) + case XMLSerialization(error: NSError) +} +``` + #### Creating a Custom Response Serializer Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. @@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/ ```swift extension Request { - public static func XMLResponseSerializer() -> ResponseSerializer { + public static func XMLResponseSerializer() -> ResponseSerializer { return ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .Failure(.Network(error: error!)) } guard let validData = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil.")) } do { let XML = try ONOXMLDocument(data: validData) return .Success(XML) } catch { - return .Failure(error as NSError) + return .Failure(.XMLSerialization(error: error as NSError)) } } } - public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) } } @@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable { } extension Request { - public func responseObject(completionHandler: Response -> Void) -> Self { - let responseSerializer = ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) @@ -737,12 +783,10 @@ extension Request { { return .Success(responseObject) } else { - let failureReason = "JSON could not be serialized into response object: \(value)" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable { ```swift Alamofire.request(.GET, "https://example.com/users/mattt") - .responseObject { (response: Response) in + .responseObject { (response: Response) in debugPrint(response) } ``` @@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable { static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] } +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] { + var collection = [Self]() + + if let representation = representation as? [[String: AnyObject]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} + extension Alamofire.Request { - public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { - let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONSerializer.serializeResponse(request, response, data, error) @@ -790,12 +850,10 @@ extension Alamofire.Request { if let response = response { return .Success(T.collection(response: response, representation: value)) } else { - let failureReason = "Response collection could not be serialized due to nil response" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable { self.username = response.URL!.lastPathComponent! self.name = representation.valueForKeyPath("name") as! String } - - static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { - var users: [User] = [] - - if let representation = representation as? [[String: AnyObject]] { - for userRepresentation in representation { - if let user = User(response: response, representation: userRepresentation) { - users.append(user) - } - } - } - - return users - } } ``` ```swift Alamofire.request(.GET, "http://example.com/users") - .responseCollection { (response: Response<[User], NSError>) in + .responseCollection { (response: Response<[User], BackendError>) in debugPrint(response) } ``` @@ -912,7 +956,7 @@ enum Router: URLRequestConvertible { var URLRequest: NSMutableURLRequest { let result: (path: String, parameters: [String: AnyObject]) = { switch self { - case .Search(let query, let page) where page > 1: + case .Search(let query, let page) where page > 0: return ("/search", ["q": query, "offset": Router.perPage * page]) case .Search(let query, _): return ("/search", ["q": query]) @@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible { Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt ``` +### SessionDelegate + +By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. +public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + +/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. +public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + +/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. +public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + +/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. +public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let delegate: Alamofire.Manager.SessionDelegate = manager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: Manager.SessionDelegate { + override func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.URLSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + ### Security Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. @@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server #### Validating the Certificate Chain -Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. @@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends > It is recommended to always use valid certificates in production environments. ---- +### Network Reachability -## Component Libraries +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") -* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +* **Do NOT** use Reachability to determine if a network request should be sent. + * You should **ALWAYS** send it. +* When Reachability is restored, use the event to retry failed network requests. + * Even though the network requests may still fail, this is a good moment to retry them. +* The network reachability status can be useful for determining why a network request may have failed. + * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- ## Open Rdars The following rdars have some affect on the current implementation of Alamofire. * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage ## FAQ @@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http:// If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +* Pay our legal fees to register as a federal non-profit organization +* Pay our yearly legal fees to keep the non-profit in good status +* Pay for our mail servers to help us stay on top of all questions and security issues +* Potentially fund test servers to make it easier for us to test the edge cases +* Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + ## License Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift index b866f42264f..cb4b36afbd3 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -1,24 +1,26 @@ -// Alamofire.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Alamofire.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift index b9a043cb8e3..97b146fc016 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -1,24 +1,26 @@ -// Download.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Download.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -211,6 +213,8 @@ extension Request { totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift index 7a813f1b813..467d99c916c 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -1,24 +1,26 @@ -// Error.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Error.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -39,6 +41,15 @@ public struct Error { case PropertyListSerializationFailed = -6007 } + /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. + public struct UserInfoKeys { + /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. + public static let ContentType = "ContentType" + + /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. + public static let StatusCode = "StatusCode" + } + /** Creates an `NSError` with the given error code and failure reason. @@ -47,6 +58,7 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } @@ -59,8 +71,18 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } + + static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { + return error(domain: domain, code: code.rawValue, failureReason: failureReason) + } + + static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: domain, code: code, userInfo: userInfo) + } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift index d81c7380fa8..691d31f62f7 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -1,24 +1,26 @@ -// Manager.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Manager.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -56,17 +58,40 @@ public class Manager { // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { - let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" - let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" - let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" - let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString - let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + let osNameVersion: String = { + let versionString: String - if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { - return mutableUserAgent as String - } + if #available(OSX 10.10, *) { + let version = NSProcessInfo.processInfo().operatingSystemVersion + versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + } else { + versionString = "10.9" + } + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(OSX) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + return "\(executable)/\(bundle) (\(version); \(osNameVersion))" } return "Alamofire" @@ -143,11 +168,11 @@ public class Manager { delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { + guard delegate === session.delegate else { return nil } + self.delegate = delegate self.session = session - guard delegate === session.delegate else { return nil } - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } @@ -218,18 +243,18 @@ public class Manager { /** Responsible for handling all delegate callbacks for the underlying session. */ - public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) - subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + /// Access the task delegate for the specified task in a thread-safe manner. + public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } - set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } @@ -254,6 +279,9 @@ public class Manager { /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. + public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? @@ -281,6 +309,11 @@ public class Manager { didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? @@ -321,11 +354,23 @@ public class Manager { /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. - public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and + /// requires the caller to call the `completionHandler`. + public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? @@ -351,8 +396,13 @@ public class Manager { task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, - completionHandler: ((NSURLRequest?) -> Void)) + completionHandler: NSURLRequest? -> Void) { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { @@ -374,10 +424,16 @@ public class Manager { session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + if let taskDidReceiveChallenge = taskDidReceiveChallenge { - completionHandler(taskDidReceiveChallenge(session, task, challenge)) + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.URLSession( session, @@ -400,8 +456,13 @@ public class Manager { public func URLSession( session: NSURLSession, task: NSURLSessionTask, - needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + needNewBodyStream completionHandler: NSInputStream? -> Void) { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { @@ -452,6 +513,8 @@ public class Manager { delegate.URLSession(session, task: task, didCompleteWithError: error) } + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) + self[task] = nil } @@ -462,6 +525,10 @@ public class Manager { /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? @@ -469,7 +536,11 @@ public class Manager { public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. - public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? // MARK: Delegate Methods @@ -487,8 +558,13 @@ public class Manager { session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, - completionHandler: ((NSURLSessionResponseDisposition) -> Void)) + completionHandler: NSURLSessionResponseDisposition -> Void) { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { @@ -550,8 +626,13 @@ public class Manager { session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, - completionHandler: ((NSCachedURLResponse?) -> Void)) + completionHandler: NSCachedURLResponse? -> Void) { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { @@ -674,17 +755,21 @@ public class Manager { // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { + #if !os(OSX) + if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + switch selector { - case "URLSession:didBecomeInvalidWithError:": + case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil - case "URLSession:didReceiveChallenge:completionHandler:": - return sessionDidReceiveChallenge != nil - case "URLSessionDidFinishEventsForBackgroundURLSession:": - return sessionDidFinishEventsForBackgroundURLSession != nil - case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": - return taskWillPerformHTTPRedirection != nil - case "URLSession:dataTask:didReceiveResponse:completionHandler:": - return dataTaskDidReceiveResponse != nil + case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespondToSelector(selector) } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift index 8c37f164e7e..b4087eca830 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -1,24 +1,26 @@ -// MultipartFormData.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// MultipartFormData.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -217,7 +219,7 @@ public class MultipartFormData { appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" - setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) } } @@ -245,8 +247,7 @@ public class MultipartFormData { guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -261,8 +262,7 @@ public class MultipartFormData { } guard isReachable else { - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") return } @@ -277,8 +277,7 @@ public class MultipartFormData { where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -301,8 +300,7 @@ public class MultipartFormData { guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -312,8 +310,7 @@ public class MultipartFormData { guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) return } @@ -413,10 +410,10 @@ public class MultipartFormData { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream @@ -425,10 +422,9 @@ public class MultipartFormData { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) } - outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true @@ -439,7 +435,6 @@ public class MultipartFormData { } outputStream.close() - outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } // MARK: - Private - Body Part Encoding @@ -476,7 +471,6 @@ public class MultipartFormData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? @@ -495,7 +489,7 @@ public class MultipartFormData { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) break } else { break @@ -503,7 +497,6 @@ public class MultipartFormData { } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { throw error @@ -537,7 +530,6 @@ public class MultipartFormData { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { @@ -556,14 +548,13 @@ public class MultipartFormData { try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } private func writeFinalBoundaryDataForBodyPart( @@ -598,7 +589,7 @@ public class MultipartFormData { if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" - throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten @@ -661,9 +652,8 @@ public class MultipartFormData { // MARK: - Private - Errors - private func setBodyPartError(error: NSError) { - if bodyPartError == nil { - bodyPartError = error - } + private func setBodyPartError(code code: Int, failureReason: String) { + guard bodyPartError == nil else { return } + bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 00000000000..1e5c7b030d3 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,244 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/** + The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and + WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to retry + network requests when a connection is established. It should not be used to prevent a user from initiating a network + request, as it's possible that an initial request may be required to establish reachability. +*/ +public class NetworkReachabilityManager { + /** + Defines the various states of network reachability. + + - Unknown: It is unknown whether the network is reachable. + - NotReachable: The network is not reachable. + - ReachableOnWWAN: The network is reachable over the WWAN connection. + - ReachableOnWiFi: The network is reachable over the WiFi connection. + */ + public enum NetworkReachabilityStatus { + case Unknown + case NotReachable + case Reachable(ConnectionType) + } + + /** + Defines the various connection types detected by reachability flags. + + - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. + - WWAN: The connection type is a WWAN connection. + */ + public enum ConnectionType { + case EthernetOrWiFi + case WWAN + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = NetworkReachabilityStatus -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .Unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /** + Creates a `NetworkReachabilityManager` instance with the specified host. + + - parameter host: The host used to evaluate network reachability. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /** + Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + + Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + status of the device, both IPv4 and IPv6. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(sizeofValue(address)) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(&address, { + SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /** + Starts listening for changes in network reachability status. + + - returns: `true` if listening was started successfully, `false` otherwise. + */ + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + dispatch_async(listenerQueue) { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /** + Stops listening for changes in network reachability status. + */ + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.Reachable) else { return .NotReachable } + + var networkStatus: NetworkReachabilityStatus = .NotReachable + + if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + + if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { + if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + } + + #if os(iOS) + if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } + #endif + + return networkStatus + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/** + Returns whether the two network reachability status values are equal. + + - parameter lhs: The left-hand side value to compare. + - parameter rhs: The right-hand side value to compare. + + - returns: `true` if the two values are equal, `false` otherwise. +*/ +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.Unknown, .Unknown): + return true + case (.NotReachable, .NotReachable): + return true + case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 00000000000..cece87a170d --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,47 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. +public struct Notifications { + /// Used as a namespace for all `NSURLSessionTask` related notifications. + public struct Task { + /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed + /// `NSURLSessionTask`. + public static let DidResume = "com.alamofire.notifications.task.didResume" + + /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the + /// suspended `NSURLSessionTask`. + public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" + + /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the + /// cancelled `NSURLSessionTask`. + public static let DidCancel = "com.alamofire.notifications.task.didCancel" + + /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the + /// completed `NSURLSessionTask`. + public static let DidComplete = "com.alamofire.notifications.task.didComplete" + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift index d56d2d6c3a7..32e63d9b7be 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -1,24 +1,26 @@ -// ParameterEncoding.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ParameterEncoding.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -69,8 +71,8 @@ public enum ParameterEncoding { /** Creates a URL request by encoding parameters and applying them onto an existing request. - - parameter URLRequest: The request to have parameters applied - - parameter parameters: The parameters to apply + - parameter URLRequest: The request to have parameters applied. + - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. @@ -82,9 +84,7 @@ public enum ParameterEncoding { { var mutableURLRequest = URLRequest.URLRequest - guard let parameters = parameters where !parameters.isEmpty else { - return (mutableURLRequest, nil) - } + guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil @@ -118,7 +118,10 @@ public enum ParameterEncoding { } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { - if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { + if let + URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) + where !parameters.isEmpty + { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL @@ -141,7 +144,10 @@ public enum ParameterEncoding { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) - mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -153,7 +159,11 @@ public enum ParameterEncoding { format: format, options: options ) - mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -219,7 +229,7 @@ public enum ParameterEncoding { //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // @@ -236,7 +246,7 @@ public enum ParameterEncoding { while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) - let range = Range(start: startIndex, end: endIndex) + let range = startIndex.. [String: String] { + guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } + + let credential = data.base64EncodedStringWithOptions([]) + + return ["Authorization": "Basic \(credential)"] + } + // MARK: - Progress /** @@ -149,17 +172,21 @@ public class Request { // MARK: - State /** - Suspends the request. + Resumes the request. */ - public func suspend() { - task.suspend() + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) } /** - Resumes the request. + Suspends the request. */ - public func resume() { - task.resume() + public func suspend() { + task.suspend() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) } /** @@ -176,6 +203,8 @@ public class Request { } else { task.cancel() } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) } // MARK: - TaskDelegate @@ -195,6 +224,7 @@ public class Request { var data: NSData? { return nil } var error: NSError? + var initialResponseTime: CFAbsoluteTime? var credential: NSURLCredential? init(task: NSURLSessionTask) { @@ -272,7 +302,7 @@ public class Request { } } else { if challenge.previousFailureCount > 0 { - disposition = .CancelAuthenticationChallenge + disposition = .RejectProtectionSpace } else { credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) @@ -381,6 +411,8 @@ public class Request { } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { @@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible { let protectionSpace = NSURLProtectionSpace( host: host, port: URL.port?.integerValue ?? 0, - `protocol`: URL.scheme, + protocol: URL.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) @@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible { } } - if let headerFields = request.allHTTPHeaderFields { - for (field, value) in headerFields { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + var headers: [NSObject: AnyObject] = [:] + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders where field != "Cookie" { + headers[field] = value } } - if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { - for (field, value) in additionalHeaders { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value } } + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + if let HTTPBodyData = request.HTTPBody, HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { - let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") + escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + components.append("-d \"\(escapedBody)\"") } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift index fa2fffb3dea..dd700bb1c82 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -1,24 +1,26 @@ -// Response.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Response.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -36,6 +38,9 @@ public struct Response { /// The result of response serialization. public let result: Result + /// The timeline of the complete lifecycle of the `Request`. + public let timeline: Timeline + /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. @@ -44,14 +49,22 @@ public struct Response { - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - + - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + - returns: the new `Response` instance. */ - public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) { + public init( + request: NSURLRequest?, + response: NSHTTPURLResponse?, + data: NSData?, + result: Result, + timeline: Timeline = Timeline()) + { self.request = request self.response = response self.data = data self.result = result + self.timeline = timeline } } @@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible { output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") return output.joinWithSeparator("\n") } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift index 4aaacf61e31..5b7b61f9002 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -1,24 +1,26 @@ -// ResponseSerialization.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ResponseSerialization.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -29,10 +31,10 @@ import Foundation */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. - typealias SerializedObject + associatedtype SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. - typealias ErrorObject: ErrorType + associatedtype ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. @@ -119,16 +121,25 @@ extension Request { self.delegate.error ) - dispatch_async(queue ?? dispatch_get_main_queue()) { - let response = Response( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result - ) + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime - completionHandler(response) - } + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: timeline + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } return self @@ -152,7 +163,7 @@ extension Request { guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -167,8 +178,12 @@ extension Request { - returns: The request. */ - public func responseData(completionHandler: Response -> Void) -> Self { - return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + public func responseData( + queue queue: dispatch_queue_t? = nil, + completionHandler: Response -> Void) + -> Self + { + return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } @@ -186,7 +201,7 @@ extension Request { - returns: A string response serializer. */ public static func stringResponseSerializer( - var encoding encoding: NSStringEncoding? = nil) + encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer { return ResponseSerializer { _, response, data, error in @@ -196,23 +211,25 @@ extension Request { guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } - - if let encodingName = response?.textEncodingName where encoding == nil { - encoding = CFStringConvertEncodingToNSStringEncoding( + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName where convertedEncoding == nil { + convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } - let actualEncoding = encoding ?? NSISOLatin1StringEncoding + let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } @@ -229,11 +246,13 @@ extension Request { - returns: The request. */ public func responseString( - encoding encoding: NSStringEncoding? = nil, + queue queue: dispatch_queue_t? = nil, + encoding: NSStringEncoding? = nil, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) @@ -263,7 +282,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -285,11 +304,13 @@ extension Request { - returns: The request. */ public func responseJSON( - options options: NSJSONReadingOptions = .AllowFragments, + queue queue: dispatch_queue_t? = nil, + options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) @@ -319,7 +340,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -343,11 +364,13 @@ extension Request { - returns: The request. */ public func responsePropertyList( - options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + queue queue: dispatch_queue_t? = nil, + options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift index a8557cabb42..ed1df0fc845 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -1,24 +1,26 @@ -// Result.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Result.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift index 07cd848a606..44ba100be43 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -1,24 +1,26 @@ -// ServerTrustPolicy.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ServerTrustPolicy.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift index bc9ee450c5a..07ebe3374ff 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -1,30 +1,32 @@ -// Stream.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Stream.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation #if !os(watchOS) -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager { private enum Streamable { case Stream(String, Int) @@ -82,7 +84,7 @@ extension Manager { // MARK: - -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager.SessionDelegate: NSURLSessionStreamDelegate { // MARK: Override Closures diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 00000000000..95936827285 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,138 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: NSTimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: NSTimeInterval + + /** + Creates a new `Timeline` instance with the specified request times. + + - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + Defaults to `0.0`. + - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + to `0.0`. + + - returns: The new `Timeline` instance. + */ + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift index ee6b34ced5b..7b31ba53073 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -1,24 +1,26 @@ -// Upload.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Upload.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -359,6 +361,8 @@ extension Request { totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift index 71d21e1afa6..e90db2d4a10 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -1,24 +1,26 @@ -// Validation.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Validation.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -80,7 +82,17 @@ extension Request { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" - return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) + + let error = NSError( + domain: Error.Domain, + code: Error.Code.StatusCodeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.StatusCode: response.statusCode + ] + ) + + return .Failure(error) } } } @@ -149,18 +161,31 @@ extension Request { } } + let contentType: String let failureReason: String if let responseContentType = response.MIMEType { + contentType = responseContentType + failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { + contentType = "" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } - return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) + let error = NSError( + domain: Error.Domain, + code: Error.Code.ContentTypeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.ContentType: contentType + ] + ) + + return .Failure(error) } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index 99bf5ef601f..0920f1985e9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -9,8 +9,8 @@ "git": "git@github.com:swagger-api/swagger-mustache.git", "tag": "v1.0.0" }, + "authors": "", "license": "Apache License, Version 2.0", - "authors": "Apache License, Version 2.0", "homepage": "https://github.com/swagger-api/swagger-codegen", "summary": "PetstoreClient", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", @@ -19,7 +19,7 @@ "~> 3.1.1" ], "Alamofire": [ - "~> 3.1.5" + "~> 3.4.1" ] } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock index 201c7e37514..0686012e4a0 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock @@ -1,14 +1,14 @@ PODS: - - Alamofire (3.1.5) - - OMGHTTPURLRQ (3.1.1): - - OMGHTTPURLRQ/RQ (= 3.1.1) - - OMGHTTPURLRQ/FormURLEncode (3.1.1) - - OMGHTTPURLRQ/RQ (3.1.1): + - Alamofire (3.4.1) + - OMGHTTPURLRQ (3.1.3): + - OMGHTTPURLRQ/RQ (= 3.1.3) + - OMGHTTPURLRQ/FormURLEncode (3.1.3) + - OMGHTTPURLRQ/RQ (3.1.3): - OMGHTTPURLRQ/FormURLEncode - OMGHTTPURLRQ/UserAgent - - OMGHTTPURLRQ/UserAgent (3.1.1) + - OMGHTTPURLRQ/UserAgent (3.1.3) - PetstoreClient (0.0.1): - - Alamofire (~> 3.1.5) + - Alamofire (~> 3.4.1) - PromiseKit (~> 3.1.1) - PromiseKit (3.1.1): - PromiseKit/Foundation (= 3.1.1) @@ -31,11 +31,11 @@ EXTERNAL SOURCES: :path: "../" SPEC CHECKSUMS: - Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 - PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace + Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c + OMGHTTPURLRQ: a547be1b9721ddfbf9d08aab56ab72dc4c1cc417 + PetstoreClient: 24135348a992f2cbd76bc324719173b52e864cdc PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 -COCOAPODS: 1.0.0 +COCOAPODS: 1.0.1 diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown index ff905517872..1cd71258ad3 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown @@ -39,7 +39,7 @@ NSData *data2 = UIImagePNGRepresentation(image2); [multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"]; // SUPER Ideally you would not want to re-encode the JPEG as the process -// is lossy. If you image comes from the AssetLibrary you *CAN* get the +// is lossy. If your image comes from the AssetLibrary you *CAN* get the // original `NSData`. See stackoverflow.com. UIImage *image3 = [UIImage imageNamed:@"image3"]; NSData *data3 = UIImageJPEGRepresentation(image3); @@ -97,7 +97,7 @@ your API keys that registering at https://dev.twitter.com will provide you. ```objc -NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com"consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; +NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com" consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; [rq addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"]; [NSURLConnection sendAsynchronousRequest:rq queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { @@ -142,4 +142,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` \ No newline at end of file +``` diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m index 0854acd0eb7..321ee61eb2e 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m @@ -47,7 +47,6 @@ - (void)add:(NSData *)payload :(NSString *)name :(NSString *)filename :(NSString [body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:payload]; - [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; } - (void)addFile:(NSData *)payload parameterName:(NSString *)name filename:(NSString *)filename contentType:(NSString *)contentType @@ -71,8 +70,8 @@ - (void)addParameters:(NSDictionary *)parameters { @implementation OMGHTTPURLRQ + (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error { - id queryString = OMGFormURLEncode(params); - if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; + NSString *queryString = OMGFormURLEncode(params); + if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; id url = [NSURL URLWithString:urlString]; if (!url) { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index b435c9a1477..1b6f460f95d 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,105 +7,108 @@ objects = { /* Begin PBXBuildFile section */ - 01BD61BBC475EB3369237B84FE24D3EE /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0268F9278E32ACC1F996F4E2E45622B5 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */; }; + 01BD61BBC475EB3369237B84FE24D3EE /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B892AF5EA37A5C7962FEA3E294B2526 /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0268F9278E32ACC1F996F4E2E45622B5 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 590BCD68D24A72708312E57A91360AC7 /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 066335E8B1AEEB4CF633B2ED738D6223 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */; }; - 06F7C0C55DF4C09C015159F6B0802EB1 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84319E048FE6DD89B905FA3A81005C5F /* join.swift */; }; - 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */ = {isa = PBXBuildFile; fileRef = 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - 0BDA43D8F48C8B0D504C440046FAF681 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0D240D796AAD10F0119A1D7AC2570AAA /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */; }; - 11C221075C5B20BDEEB3DDF8EAC99E63 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */; }; - 11EA8D6B0352FD31F520F983CFB9D993 /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */; }; - 12348513CB81BD05B497C210905CDF65 /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 124EFF5E3C46EC88F47C52479FA6ACAF /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */; }; + 06F7C0C55DF4C09C015159F6B0802EB1 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = BED547C24FF8AE5F91ED94E3BC8052C8 /* join.swift */; }; + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7390892336E4D605CF390FFA4B55EF0A /* Error.swift */; }; + 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */ = {isa = PBXBuildFile; fileRef = 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0BDA43D8F48C8B0D504C440046FAF681 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B0B08C036B6283A3D528F1FBBEEF40EC /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0D240D796AAD10F0119A1D7AC2570AAA /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6650152803DA41F52DA6A26B5DF713D7 /* NSObject+Promise.swift */; }; + 11C221075C5B20BDEEB3DDF8EAC99E63 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = DCBC249F9443D7D79A42B5C4BAC874C8 /* NSNotificationCenter+AnyPromise.m */; }; + 11EA8D6B0352FD31F520F983CFB9D993 /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FB7C011EC5C968D7A91E71A028913B7 /* UIAlertView+AnyPromise.m */; }; + 12348513CB81BD05B497C210905CDF65 /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E19A7D44620C4AED963248648938767 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 124EFF5E3C46EC88F47C52479FA6ACAF /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = DD83C2B5FF3BF5AB85E18B1BB6293857 /* CALayer+AnyPromise.m */; }; 15ECEBA1EFBD023AEA47F36524270D2C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; - 18FAC6B4FD3B44CB353C7A6027286100 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 1AC7E88F0EC64D1D4E83CE7767BFD2B7 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */; }; + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47B728204DA3D60FAB04A757D3B09D2E /* Timeline.swift */; }; + 18FAC6B4FD3B44CB353C7A6027286100 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E0B0C8D6D1D56B95983D680363E6F785 /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1AC7E88F0EC64D1D4E83CE7767BFD2B7 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = 178262A3EEE3B9A6F7B9B2B4ED5AA150 /* afterlife.swift */; }; 1CB5E10963E95432A9674D1FF2B48FA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; 1CDA074C6DC95876D85E13ECF882B93A /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; - 1E1010EA437F154A554D04F7F3A894EC /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */; }; + 1E1010EA437F154A554D04F7F3A894EC /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = B225BF6ADAA247F1300081D25732B5B4 /* Promise+Properties.swift */; }; 25FBB92AFB8F5A777CE8E40EC3B9DACA /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; 2B38BB4603B4286FF8D7A780372E947F /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0435721889B71489503A007D233559DF /* Validation.swift */; }; 2D9379807BA243E1CE457D1BE963DA09 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; - 3860D960E37C1257BDA54626CA592E86 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 387C7387FDC662D23D743879B6143D59 /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */; }; - 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFB0686D05BA9C4D5A69D6058C029FF2 /* NetworkReachabilityManager.swift */; }; + 3860D960E37C1257BDA54626CA592E86 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = D475FE9899956F5D2196D1C19DFC1F28 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 387C7387FDC662D23D743879B6143D59 /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDDBF73F440D96AB666A6418AEEF2946 /* UIActionSheet+Promise.swift */; }; + 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FF818D195F8814F5F8878A2FD02AF1D /* OMGUserAgent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA62734652B80C3897AA655226B3BCF3 /* ResponseSerialization.swift */; }; + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AA002805CE140B0968FC965A53F0A4C /* Manager.swift */; }; 443361437B359830308B93A7B98BE039 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; 46F838880F41F56ABD91796FC956B4BF /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; - 48CB8E7E16443CA771E4DCFB3E0709A2 /* OMGHTTPURLRQ.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 4C22563311AC2B52651A6525A979E076 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */; }; - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */; }; + 48CB8E7E16443CA771E4DCFB3E0709A2 /* OMGHTTPURLRQ.m in Sources */ = {isa = PBXBuildFile; fileRef = 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 4C22563311AC2B52651A6525A979E076 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = EA13BF2FADA101A1AB34BF5EC8C7BA85 /* UIView+AnyPromise.m */; }; 516D41E4D035A817CC5116C11302E408 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; - 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */ = {isa = PBXBuildFile; fileRef = 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5D7EAE5725A7E750B51FD27AECB5F0FD /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 6AD59903FAA8315AD0036AC459FFB97F /* join.m */; }; + 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3029ADF04ADC2B8F3A7264A416D70B56 /* OMGHTTPURLRQ-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E0C3DC76C639C91EF9B920C8E3D60F /* Upload.swift */; }; + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 770621722C3B98D9380F76F3310EAA7F /* Download.swift */; }; + 5D7EAE5725A7E750B51FD27AECB5F0FD /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = E3B8EDBFFE2A701981A073412ECCF6AD /* join.m */; }; 5EE5E1CA27F3CB04A5DCF5BB90B76000 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; - 5FFED823C0BDD412FA41B01EA47394D1 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */; }; - 60EBBACB76CD5879FB7B9B3E0AA5E2C1 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */; }; + 5FFED823C0BDD412FA41B01EA47394D1 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = 955F5499BB7496155FBF443B524F1D50 /* hang.m */; }; + 60EBBACB76CD5879FB7B9B3E0AA5E2C1 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 53F1201EF49979297542207D6EB6EC55 /* UIViewController+AnyPromise.m */; }; + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74E1D5C24530737CDD54FA854E37B371 /* Response.swift */; }; 656BED6137A9FFA3B2DF03861F525022 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 6A128FE350973D8A693E3F063C5E4A49 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */; }; + 6A128FE350973D8A693E3F063C5E4A49 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = 7356B0365E4182E6E6D55124C678B591 /* dispatch_promise.m */; }; 6B0A17CD24331793D2504E0FBBAF5EB2 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; - 6CB84A616D7B4D189A4E94BD37621575 /* OMGUserAgent.m in Sources */ = {isa = PBXBuildFile; fileRef = E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 6F63943B0E954F701F32BC7A1F4C2FEC /* OMGFormURLEncode.m in Sources */ = {isa = PBXBuildFile; fileRef = 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 73FA79FDB37E5C458B996012BFB0CF04 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */; }; + 6CB84A616D7B4D189A4E94BD37621575 /* OMGUserAgent.m in Sources */ = {isa = PBXBuildFile; fileRef = 937CB6976C5F585A76A9383107F5AF73 /* OMGUserAgent.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 6F63943B0E954F701F32BC7A1F4C2FEC /* OMGFormURLEncode.m in Sources */ = {isa = PBXBuildFile; fileRef = 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 73FA79FDB37E5C458B996012BFB0CF04 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0608A7843513940A299A88D778388F9D /* PMKAlertController.swift */; }; + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D1D96AB285E285A3CC15FAD1CD875B2 /* ServerTrustPolicy.swift */; }; 7D7A40DBAC93241786E8C553921E8C86 /* OMGHTTPURLRQ.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */; }; - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */; }; - 81A2DB65C0742D785DE7C2609CC14140 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */; }; + 81A2DB65C0742D785DE7C2609CC14140 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A5AEB5CADDFFFC419A0D8D6FD914800 /* NSURLSession+Promise.swift */; }; 825D1C93689636D09044C5077E5D905F /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */; }; - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */; }; - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */; }; - 857E5961D9F6E23BD86DEB613A1499C7 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 88B3F911629C08DEEB226F3B294AAB36 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */; }; + 857E5961D9F6E23BD86DEB613A1499C7 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E9E05F82273A09FD6E5CA99FD3A74D9 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 88B3F911629C08DEEB226F3B294AAB36 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 786AAA1F62613C489FD473D4CE16127A /* NSNotificationCenter+Promise.swift */; }; 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8C4A96A3E69C772990E3E922D0FD1BC4 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8D3A68D3CBD8A1D89099F704A04A04FC /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */; }; - 8E3861989641484EE3095722EC08B5A9 /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */; }; - 909B0A29022956D90C32C4AA319F75D1 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */; }; - 97D71F12142A541BEEF425805D51379E /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */; }; + 8C4A96A3E69C772990E3E922D0FD1BC4 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DB7D7990FD3354E34510894CC30CD1 /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8D3A68D3CBD8A1D89099F704A04A04FC /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */; }; + 8E3861989641484EE3095722EC08B5A9 /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = D9A940E08D42AC7D07C6B74D3310C69A /* NSURLConnection+AnyPromise.m */; }; + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDA7C65B58A0E739E615FA7A750AA0AD /* Alamofire.swift */; }; + 909B0A29022956D90C32C4AA319F75D1 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = EC8150042B23FCA7DF9979098694EC0B /* AnyPromise.m */; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 791F2A99A7894F88F8BBAE2F6C627522 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 97D71F12142A541BEEF425805D51379E /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EC07412ABFB8D5A06E7B38380FFD9C4 /* race.swift */; }; 9876AE0817723FB5E93A94B1E1906901 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; 9CFBA896DF45B68C788F80013AC3FDBB /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */; }; - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */; }; - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = A04177B09D9596450D827FE49A36C4C4 /* Download.swift */; }; A4BA36ADDDFBCF208CC58E552C0AC85C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - ADEEE5F368B5D707D03E78FD75C59048 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */; }; - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */; }; - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */; }; + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F60254382C7024DDFD16533FB81750A /* Result.swift */; }; + ADEEE5F368B5D707D03E78FD75C59048 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDB573F3C977C55072704AA24EC06164 /* Promise.swift */; }; + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F0962CCF21BDD2EB5751C14F9322AFC9 /* Alamofire-dummy.m */; }; + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCC88BB5150F5865EE3017D1B9AB4CF5 /* Stream.swift */; }; + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9519BB8B059D8A17CE43587EB6EFA61D /* Notifications.swift */; }; + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B2CF9B72BC56E74E6B0037BDE92031 /* ParameterEncoding.swift */; }; C141DD535C090B58DD95D53988AAA42B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */; }; - C86881D2285095255829A578F0A85300 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = B868468092D7B2489B889A50981C9247 /* after.m */; }; - C86CE0A47FAD4C9B2929A335D62A179E /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */; }; - CAF12A3EDA2376FFEAD4A12E413C1AAD /* UIActionSheet+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */; }; - CB2A58CBAB5A2E63D0CB70F2697CAE87 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */; }; + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA79CBD1DDA33C45473F8807605719BC /* MultipartFormData.swift */; }; + C86881D2285095255829A578F0A85300 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 4765491FCD8E096D84D4E57E005B8B49 /* after.m */; }; + C86CE0A47FAD4C9B2929A335D62A179E /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7C40ADE30634419CED97EC829EE5D2C /* UIViewController+Promise.swift */; }; + CAF12A3EDA2376FFEAD4A12E413C1AAD /* UIActionSheet+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = CABB6C822D84DC5F0596B6D7B60CC5AA /* UIActionSheet+AnyPromise.m */; }; + CB2A58CBAB5A2E63D0CB70F2697CAE87 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 9C307C0A58A490D3080DB4C1E745C973 /* when.m */; }; CD97970D21D3CB8C459FAFEF11EE60F3 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; - CE225CF07E6E385F014883D607AFA44D /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */; }; - CE89E5C528D52BBCBCD23309603BA6D1 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - D1735D6C4D574339EB49024228448459 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */; }; - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */; }; - D358A828E68E152D06FC8E35533BF00B /* OMGHTTPURLRQ-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */; }; + CE225CF07E6E385F014883D607AFA44D /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E339112CF5C9275CFBEB94C29AD250B /* URLDataPromise.swift */; }; + CE89E5C528D52BBCBCD23309603BA6D1 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E48946E76C93EE81F20C76C0EE272B8E /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D1735D6C4D574339EB49024228448459 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E69FDAAF09817F0BA67D7C575BAFF48 /* UIView+Promise.swift */; }; + D358A828E68E152D06FC8E35533BF00B /* OMGHTTPURLRQ-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8F88352C39FB2D4A0D36696674E7C05D /* OMGHTTPURLRQ-dummy.m */; }; D546A4DBA3F7750F45A6F63B994C081C /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */; }; - D93596046CD3B301F4EC99A7A118C82C /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */; }; + D93596046CD3B301F4EC99A7A118C82C /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFFF6310B8F8C445362FF33E936F85CA /* Error.swift */; }; D97B0097ACB39F4E308E996F4F2AC836 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - DBD1F4247E1C591AE4EE5531599AB170 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DBD1F4247E1C591AE4EE5531599AB170 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = EFC77A5BCF407679FAB606F03E631A11 /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; E2B0094FAAEA55C55AD141136F650E35 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; EA35E77B4F31DC3E1D224458E0BC959D /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; - EA67B414E392EFD2B14742F55A595596 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */; }; - EB3C88CDAF122BA763FEF85758370C7C /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */; }; - EB9A1F33DB49ADA09F6E7F19A2C30357 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */; }; - ED30A8B82BA1D53CBC370B1DC18DA1EB /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16730DAF3E51C161D8247E473F069E71 /* when.swift */; }; + EA67B414E392EFD2B14742F55A595596 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E49ED544745AD479AFA0B6766F441CE /* after.swift */; }; + EB3C88CDAF122BA763FEF85758370C7C /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E29EB54AEC61300AD412C40991FFED5 /* UIAlertView+Promise.swift */; }; + EB9A1F33DB49ADA09F6E7F19A2C30357 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9066E09FAD7A3236DAD81317C1E48214 /* NSURLConnection+Promise.swift */; }; + ED30A8B82BA1D53CBC370B1DC18DA1EB /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEFA2BBF978F33CA2112DC5D6209A3EF /* when.swift */; }; + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D3192434754120C2AAF44818AEE054B /* Request.swift */; }; F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - F4582E8DC1C9F362ADA4BAE9CEF8B681 /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */; }; - F700EAA9F9F6C1F99C83B45D05C5AD14 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F7161E50F083B2267363F243C4E4B78F /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */; }; - F898D4270885EF1114608E76B0C09E21 /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */; }; + F4582E8DC1C9F362ADA4BAE9CEF8B681 /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85FD17541BFB4152FD5F2CA46F9E3ACC /* dispatch_promise.swift */; }; + F700EAA9F9F6C1F99C83B45D05C5AD14 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 1AAED38B682D186542DC2B8D273486F4 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F7161E50F083B2267363F243C4E4B78F /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FB5ABB73E12675999DE989CC2478A7A /* AnyPromise.swift */; }; + F898D4270885EF1114608E76B0C09E21 /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BEE20F7C5242E616D2D97B5FBE31323 /* State.swift */; }; FB0B33F03AC2BC8A7FC7FD912C12CC22 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */; }; - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */; }; - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */; }; FFA95B8BEE43D793FF453E49099AC52E /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0B92202857E3535647B0785253083518 /* QuartzCore.framework */; }; /* End PBXBuildFile section */ @@ -114,7 +117,7 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; 6795BDA8BF074DFC4E5D1758C8F88C2A /* PBXContainerItemProxy */ = { @@ -142,7 +145,7 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; ABF692D458113B268763EDC4670EAF7A /* PBXContainerItemProxy */ = { @@ -164,138 +167,141 @@ /* Begin PBXFileReference section */ 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; - 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+Cancellation.h"; path = "Sources/NSError+Cancellation.h"; sourceTree = ""; }; - 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "CALayer+AnyPromise.m"; path = "Categories/QuartzCore/CALayer+AnyPromise.m"; sourceTree = ""; }; + 0435721889B71489503A007D233559DF /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 0608A7843513940A299A88D778388F9D /* PMKAlertController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PMKAlertController.swift; path = Categories/UIKit/PMKAlertController.swift; sourceTree = ""; }; 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; - 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Umbrella.h; path = Sources/Umbrella.h; sourceTree = ""; }; 0B92202857E3535647B0785253083518 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; - 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Categories/UIKit/UIViewController+AnyPromise.h"; sourceTree = ""; }; 0C552CDBDD89D489D23D5D4E28356F84 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "OMGHTTPURLRQ-dummy.m"; sourceTree = ""; }; - 122D5005A81832479161CD1D223C573A /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; - 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; - 16730DAF3E51C161D8247E473F069E71 /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; - 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = OMGHTTPURLRQ.xcconfig; sourceTree = ""; }; + 0E339112CF5C9275CFBEB94C29AD250B /* URLDataPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLDataPromise.swift; path = Sources/URLDataPromise.swift; sourceTree = ""; }; + 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 11683764D40FE241FCEEB379EE92E817 /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; + 13DB7D7990FD3354E34510894CC30CD1 /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Categories/UIKit/UIView+AnyPromise.h"; sourceTree = ""; }; + 178262A3EEE3B9A6F7B9B2B4ED5AA150 /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Categories/Foundation/afterlife.swift; sourceTree = ""; }; 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; - 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; - 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; - 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 1AA002805CE140B0968FC965A53F0A4C /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + 1AAED38B682D186542DC2B8D273486F4 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; + 1F60254382C7024DDFD16533FB81750A /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 1FB5ABB73E12675999DE989CC2478A7A /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; - 24C79ED4B5226F263307B22E96E88F9F /* OMGHTTPURLRQ.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = OMGHTTPURLRQ.modulemap; sourceTree = ""; }; - 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGFormURLEncode.m; path = Sources/OMGFormURLEncode.m; sourceTree = ""; }; 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; - 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; - 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "CALayer+AnyPromise.h"; path = "Categories/QuartzCore/CALayer+AnyPromise.h"; sourceTree = ""; }; 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; - 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; - 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Categories/UIKit/UIView+AnyPromise.m"; sourceTree = ""; }; + 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; + 2E9E05F82273A09FD6E5CA99FD3A74D9 /* NSError+Cancellation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+Cancellation.h"; path = "Sources/NSError+Cancellation.h"; sourceTree = ""; }; 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; - 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 3029ADF04ADC2B8F3A7264A416D70B56 /* OMGHTTPURLRQ-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-umbrella.h"; sourceTree = ""; }; 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; - 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; - 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = dispatch_promise.swift; path = Sources/dispatch_promise.swift; sourceTree = ""; }; - 3950B63B8EB1B9CD8FC31CDA8CC2E7C7 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; - 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; - 3CE589B7B1FE57084403D25DC49528B5 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGFormURLEncode.h; path = Sources/OMGFormURLEncode.h; sourceTree = ""; }; + 3BEE20F7C5242E616D2D97B5FBE31323 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; + 3E49ED544745AD479AFA0B6766F441CE /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; + 3EC07412ABFB8D5A06E7B38380FFD9C4 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGHTTPURLRQ.m; path = Sources/OMGHTTPURLRQ.m; sourceTree = ""; }; 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLConnection+Promise.swift"; path = "Categories/Foundation/NSURLConnection+Promise.swift"; sourceTree = ""; }; 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; - 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGHTTPURLRQ.h; path = Sources/OMGHTTPURLRQ.h; sourceTree = ""; }; + 467F288FF1A023115720F192FD4D9297 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; - 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; - 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGFormURLEncode.h; path = Sources/OMGFormURLEncode.h; sourceTree = ""; }; - 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Categories/Foundation/NSURLSession+Promise.swift"; sourceTree = ""; }; - 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 4765491FCD8E096D84D4E57E005B8B49 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; + 47B728204DA3D60FAB04A757D3B09D2E /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 4E19A7D44620C4AED963248648938767 /* UIAlertView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AnyPromise.h"; path = "Categories/UIKit/UIAlertView+AnyPromise.h"; sourceTree = ""; }; + 4FF818D195F8814F5F8878A2FD02AF1D /* OMGUserAgent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGUserAgent.h; path = Sources/OMGUserAgent.h; sourceTree = ""; }; + 53F1201EF49979297542207D6EB6EC55 /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Categories/UIKit/UIViewController+AnyPromise.m"; sourceTree = ""; }; 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; - 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; - 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; + 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGFormURLEncode.m; path = Sources/OMGFormURLEncode.m; sourceTree = ""; }; + 590BCD68D24A72708312E57A91360AC7 /* UIActionSheet+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActionSheet+AnyPromise.h"; path = "Categories/UIKit/UIActionSheet+AnyPromise.h"; sourceTree = ""; }; + 5A5AEB5CADDFFFC419A0D8D6FD914800 /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Categories/Foundation/NSURLSession+Promise.swift"; sourceTree = ""; }; 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; - 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActionSheet+AnyPromise.h"; path = "Categories/UIKit/UIActionSheet+AnyPromise.h"; sourceTree = ""; }; + 5E69FDAAF09817F0BA67D7C575BAFF48 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Categories/UIKit/UIView+Promise.swift"; sourceTree = ""; }; + 6650152803DA41F52DA6A26B5DF713D7 /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Categories/Foundation/NSObject+Promise.swift"; sourceTree = ""; }; 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; - 6AD59903FAA8315AD0036AC459FFB97F /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; - 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 705D1370384B46A3E5A39B39E7B4D181 /* OMGHTTPURLRQ-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-prefix.pch"; sourceTree = ""; }; + 7356B0365E4182E6E6D55124C678B591 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; + 7390892336E4D605CF390FFA4B55EF0A /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 74E1D5C24530737CDD54FA854E37B371 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 770621722C3B98D9380F76F3310EAA7F /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 786AAA1F62613C489FD473D4CE16127A /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Categories/Foundation/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; + 791F2A99A7894F88F8BBAE2F6C627522 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 7B892AF5EA37A5C7962FEA3E294B2526 /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Categories/UIKit/UIViewController+AnyPromise.h"; sourceTree = ""; }; 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; - 84319E048FE6DD89B905FA3A81005C5F /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; + 7D3192434754120C2AAF44818AEE054B /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 835E52C658674D7A44ED95B966432726 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGHTTPURLRQ.h; path = Sources/OMGHTTPURLRQ.h; sourceTree = ""; }; + 85FD17541BFB4152FD5F2CA46F9E3ACC /* dispatch_promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = dispatch_promise.swift; path = Sources/dispatch_promise.swift; sourceTree = ""; }; 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 8749F40CC17CE0C26C36B0F431A9C8F0 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGUserAgent.h; path = Sources/OMGUserAgent.h; sourceTree = ""; }; - 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; - 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; - 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; + 8D1D96AB285E285A3CC15FAD1CD875B2 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 8E29EB54AEC61300AD412C40991FFED5 /* UIAlertView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIAlertView+Promise.swift"; path = "Categories/UIKit/UIAlertView+Promise.swift"; sourceTree = ""; }; 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; - 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + 8F8078A9DEC41CD886A8676D889912A4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8F88352C39FB2D4A0D36696674E7C05D /* OMGHTTPURLRQ-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "OMGHTTPURLRQ-dummy.m"; sourceTree = ""; }; + 9066E09FAD7A3236DAD81317C1E48214 /* NSURLConnection+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLConnection+Promise.swift"; path = "Categories/Foundation/NSURLConnection+Promise.swift"; sourceTree = ""; }; 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; - 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AnyPromise.h"; path = "Categories/UIKit/UIAlertView+AnyPromise.h"; sourceTree = ""; }; + 937CB6976C5F585A76A9383107F5AF73 /* OMGUserAgent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGUserAgent.m; path = Sources/OMGUserAgent.m; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 94F9363EEBC7855FA6B9A6B7485D5170 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9519BB8B059D8A17CE43587EB6EFA61D /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 955F5499BB7496155FBF443B524F1D50 /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActionSheet+AnyPromise.m"; path = "Categories/UIKit/UIActionSheet+AnyPromise.m"; sourceTree = ""; }; 97FF5C0140A433518CF653B6A520F27A /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; - 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGHTTPURLRQ.m; path = Sources/OMGHTTPURLRQ.m; sourceTree = ""; }; + 9C307C0A58A490D3080DB4C1E745C973 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; - A04177B09D9596450D827FE49A36C4C4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 9FB7C011EC5C968D7A91E71A028913B7 /* UIAlertView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIAlertView+AnyPromise.m"; path = "Categories/UIKit/UIAlertView+AnyPromise.m"; sourceTree = ""; }; A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLConnection+AnyPromise.m"; path = "Categories/Foundation/NSURLConnection+AnyPromise.m"; sourceTree = ""; }; - A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; - AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Categories/UIKit/UIViewController+AnyPromise.m"; sourceTree = ""; }; - AB4DA378490493502B34B20D4B12325B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A9E0C3DC76C639C91EF9B920C8E3D60F /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + B0B08C036B6283A3D528F1FBBEEF40EC /* Umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Umbrella.h; path = Sources/Umbrella.h; sourceTree = ""; }; + B225BF6ADAA247F1300081D25732B5B4 /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; + B349821C1F2B2C5F593BC228C462C99D /* OMGHTTPURLRQ.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = OMGHTTPURLRQ.modulemap; sourceTree = ""; }; B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; - B868468092D7B2489B889A50981C9247 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; - B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Categories/Foundation/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; - B9E21DC1171D712B2D2307EE5034D99E /* OMGHTTPURLRQ-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-prefix.pch"; sourceTree = ""; }; - BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLConnection+AnyPromise.h"; path = "Categories/Foundation/NSURLConnection+AnyPromise.h"; sourceTree = ""; }; - BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Categories/UIKit/UIView+AnyPromise.h"; sourceTree = ""; }; + B7C40ADE30634419CED97EC829EE5D2C /* UIViewController+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Promise.swift"; path = "Categories/UIKit/UIViewController+Promise.swift"; sourceTree = ""; }; + BCC88BB5150F5865EE3017D1B9AB4CF5 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; - C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Categories/Foundation/afterlife.swift; sourceTree = ""; }; - C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PMKAlertController.swift; path = Categories/UIKit/PMKAlertController.swift; sourceTree = ""; }; - CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIAlertView+Promise.swift"; path = "Categories/UIKit/UIAlertView+Promise.swift"; sourceTree = ""; }; - CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; - CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; - CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; + BDEAF9E48610133B23BB992381D0E22B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + BED547C24FF8AE5F91ED94E3BC8052C8 /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; + CA79CBD1DDA33C45473F8807605719BC /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + CABB6C822D84DC5F0596B6D7B60CC5AA /* UIActionSheet+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActionSheet+AnyPromise.m"; path = "Categories/UIKit/UIActionSheet+AnyPromise.m"; sourceTree = ""; }; CF8754792D6C49D6F5C8859350F48B35 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + D3A577E7C7DF4A2157D9001CA0D40A72 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; + D475FE9899956F5D2196D1C19DFC1F28 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; - D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Promise.swift"; path = "Categories/UIKit/UIViewController+Promise.swift"; sourceTree = ""; }; - D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Categories/Foundation/NSObject+Promise.swift"; sourceTree = ""; }; D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + D9A940E08D42AC7D07C6B74D3310C69A /* NSURLConnection+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLConnection+AnyPromise.m"; path = "Categories/Foundation/NSURLConnection+AnyPromise.m"; sourceTree = ""; }; + DA62734652B80C3897AA655226B3BCF3 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DCBC249F9443D7D79A42B5C4BAC874C8 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; + DD83C2B5FF3BF5AB85E18B1BB6293857 /* CALayer+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "CALayer+AnyPromise.m"; path = "Categories/QuartzCore/CALayer+AnyPromise.m"; sourceTree = ""; }; + DDB573F3C977C55072704AA24EC06164 /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + DDDBF73F440D96AB666A6418AEEF2946 /* UIActionSheet+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActionSheet+Promise.swift"; path = "Categories/UIKit/UIActionSheet+Promise.swift"; sourceTree = ""; }; DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; - E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGUserAgent.m; path = Sources/OMGUserAgent.m; sourceTree = ""; }; + DEFA2BBF978F33CA2112DC5D6209A3EF /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; + DFFF6310B8F8C445362FF33E936F85CA /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; + E0B0C8D6D1D56B95983D680363E6F785 /* NSURLConnection+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLConnection+AnyPromise.h"; path = "Categories/Foundation/NSURLConnection+AnyPromise.h"; sourceTree = ""; }; E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; - E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Categories/UIKit/UIView+Promise.swift"; sourceTree = ""; }; + E3B8EDBFFE2A701981A073412ECCF6AD /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; + E48946E76C93EE81F20C76C0EE272B8E /* CALayer+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "CALayer+AnyPromise.h"; path = "Categories/QuartzCore/CALayer+AnyPromise.h"; sourceTree = ""; }; + E4B2CF9B72BC56E74E6B0037BDE92031 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; - E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLDataPromise.swift; path = Sources/URLDataPromise.swift; sourceTree = ""; }; - F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIAlertView+AnyPromise.m"; path = "Categories/UIKit/UIAlertView+AnyPromise.m"; sourceTree = ""; }; + E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = OMGHTTPURLRQ.xcconfig; sourceTree = ""; }; + EA13BF2FADA101A1AB34BF5EC8C7BA85 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Categories/UIKit/UIView+AnyPromise.m"; sourceTree = ""; }; + EC8150042B23FCA7DF9979098694EC0B /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; + EFC77A5BCF407679FAB606F03E631A11 /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; + F0962CCF21BDD2EB5751C14F9322AFC9 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; - F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-umbrella.h"; sourceTree = ""; }; FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; - FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActionSheet+Promise.swift"; path = "Categories/UIKit/UIActionSheet+Promise.swift"; sourceTree = ""; }; + FDA7C65B58A0E739E615FA7A750AA0AD /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FFB0686D05BA9C4D5A69D6058C029FF2 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -315,11 +321,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -355,6 +361,15 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 00ED77B3FFE891B16DC5B4DD2FCC0408 /* UserAgent */ = { + isa = PBXGroup; + children = ( + 4FF818D195F8814F5F8878A2FD02AF1D /* OMGUserAgent.h */, + 937CB6976C5F585A76A9383107F5AF73 /* OMGUserAgent.m */, + ); + name = UserAgent; + sourceTree = ""; + }; 01A9CB10E1E9A90B6A796034AF093E8C /* Products */ = { isa = PBXGroup; children = ( @@ -368,15 +383,6 @@ name = Products; sourceTree = ""; }; - 07467E828160702D1DB7EC2F492C337C /* UserAgent */ = { - isa = PBXGroup; - children = ( - 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */, - E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */, - ); - name = UserAgent; - sourceTree = ""; - }; 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { isa = PBXGroup; children = ( @@ -389,18 +395,25 @@ path = Models; sourceTree = ""; }; - 1D2330E920AD5F6E4655BE449D006A77 /* Support Files */ = { + 188F1582EFF9CD3E8AB3A7470820B51F /* PromiseKit */ = { isa = PBXGroup; children = ( - AB4DA378490493502B34B20D4B12325B /* Info.plist */, - 24C79ED4B5226F263307B22E96E88F9F /* OMGHTTPURLRQ.modulemap */, - 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */, - 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */, - B9E21DC1171D712B2D2307EE5034D99E /* OMGHTTPURLRQ-prefix.pch */, - F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */, + 72B5E9FE2F2C23CD28C86A837D09964A /* CorePromise */, + 79A7166061336F6A7FF214DB285A9584 /* Foundation */, + 2115C8F445286DAD6754A21C2ABE2E78 /* QuartzCore */, + 977CD7DB18C38452FB8DCFCEC690CBDE /* Support Files */, + 933F0A2EBD44D53190D1E9FAF3F54AFB /* UIKit */, ); - name = "Support Files"; - path = "../Target Support Files/OMGHTTPURLRQ"; + path = PromiseKit; + sourceTree = ""; + }; + 2115C8F445286DAD6754A21C2ABE2E78 /* QuartzCore */ = { + isa = PBXGroup; + children = ( + E48946E76C93EE81F20C76C0EE272B8E /* CALayer+AnyPromise.h */, + DD83C2B5FF3BF5AB85E18B1BB6293857 /* CALayer+AnyPromise.m */, + ); + name = QuartzCore; sourceTree = ""; }; 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { @@ -411,65 +424,120 @@ name = "Development Pods"; sourceTree = ""; }; - 76DC20E0A9F8CDC0E47176B58A9C5BD5 /* Foundation */ = { + 27098387544928716460DD8F5024EE8A /* Pods */ = { isa = PBXGroup; children = ( - C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */, - 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */, - 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */, - B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */, - D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */, - BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */, - A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */, - 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */, - 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */, + 41488276780D879BE61AA0617BDC29A0 /* Alamofire */, + 6C55196C7E1A0F95D0BEFD790EA1450C /* OMGHTTPURLRQ */, + 188F1582EFF9CD3E8AB3A7470820B51F /* PromiseKit */, ); - name = Foundation; + name = Pods; sourceTree = ""; }; - 7DB346D0F39D3F0E887471402A8071AB = { + 41488276780D879BE61AA0617BDC29A0 /* Alamofire */ = { isa = PBXGroup; children = ( - 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, - 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, - E85F5154C248966A1EC7B7B6EACB20CF /* Frameworks */, - CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */, - 01A9CB10E1E9A90B6A796034AF093E8C /* Products */, - C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + FDA7C65B58A0E739E615FA7A750AA0AD /* Alamofire.swift */, + 770621722C3B98D9380F76F3310EAA7F /* Download.swift */, + 7390892336E4D605CF390FFA4B55EF0A /* Error.swift */, + 1AA002805CE140B0968FC965A53F0A4C /* Manager.swift */, + CA79CBD1DDA33C45473F8807605719BC /* MultipartFormData.swift */, + FFB0686D05BA9C4D5A69D6058C029FF2 /* NetworkReachabilityManager.swift */, + 9519BB8B059D8A17CE43587EB6EFA61D /* Notifications.swift */, + E4B2CF9B72BC56E74E6B0037BDE92031 /* ParameterEncoding.swift */, + 7D3192434754120C2AAF44818AEE054B /* Request.swift */, + 74E1D5C24530737CDD54FA854E37B371 /* Response.swift */, + DA62734652B80C3897AA655226B3BCF3 /* ResponseSerialization.swift */, + 1F60254382C7024DDFD16533FB81750A /* Result.swift */, + 8D1D96AB285E285A3CC15FAD1CD875B2 /* ServerTrustPolicy.swift */, + BCC88BB5150F5865EE3017D1B9AB4CF5 /* Stream.swift */, + 47B728204DA3D60FAB04A757D3B09D2E /* Timeline.swift */, + A9E0C3DC76C639C91EF9B920C8E3D60F /* Upload.swift */, + 0435721889B71489503A007D233559DF /* Validation.swift */, + DFFDACE0170FB00C7ECFDA52A87A7665 /* Support Files */, ); + path = Alamofire; sourceTree = ""; }; - 7DFF028D9F7D443B2361EBEDACC99624 /* OMGHTTPURLRQ */ = { + 45199ED47CEA398ADDDFDE8F9D0A591D /* Support Files */ = { isa = PBXGroup; children = ( - 8FCF5C41226503429E7875DF4CA4D36E /* FormURLEncode */, - A00A425F2E132E8FF4DE929E7DF9CC1E /* RQ */, - 1D2330E920AD5F6E4655BE449D006A77 /* Support Files */, - 07467E828160702D1DB7EC2F492C337C /* UserAgent */, + 8F8078A9DEC41CD886A8676D889912A4 /* Info.plist */, + B349821C1F2B2C5F593BC228C462C99D /* OMGHTTPURLRQ.modulemap */, + E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */, + 8F88352C39FB2D4A0D36696674E7C05D /* OMGHTTPURLRQ-dummy.m */, + 705D1370384B46A3E5A39B39E7B4D181 /* OMGHTTPURLRQ-prefix.pch */, + 3029ADF04ADC2B8F3A7264A416D70B56 /* OMGHTTPURLRQ-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/OMGHTTPURLRQ"; + sourceTree = ""; + }; + 6C55196C7E1A0F95D0BEFD790EA1450C /* OMGHTTPURLRQ */ = { + isa = PBXGroup; + children = ( + B00B1E51F2524127FFF78DB52869057E /* FormURLEncode */, + 9466970616DD9491B9B80845EBAF6997 /* RQ */, + 45199ED47CEA398ADDDFDE8F9D0A591D /* Support Files */, + 00ED77B3FFE891B16DC5B4DD2FCC0408 /* UserAgent */, ); path = OMGHTTPURLRQ; sourceTree = ""; }; - 81B1E3A8E00502B38EACDE3617A7A73B /* Support Files */ = { + 72B5E9FE2F2C23CD28C86A837D09964A /* CorePromise */ = { isa = PBXGroup; children = ( - 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */, - CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */, - CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */, - 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */, - 122D5005A81832479161CD1D223C573A /* PromiseKit-prefix.pch */, + 4765491FCD8E096D84D4E57E005B8B49 /* after.m */, + 3E49ED544745AD479AFA0B6766F441CE /* after.swift */, + D475FE9899956F5D2196D1C19DFC1F28 /* AnyPromise.h */, + EC8150042B23FCA7DF9979098694EC0B /* AnyPromise.m */, + 1FB5ABB73E12675999DE989CC2478A7A /* AnyPromise.swift */, + 7356B0365E4182E6E6D55124C678B591 /* dispatch_promise.m */, + 85FD17541BFB4152FD5F2CA46F9E3ACC /* dispatch_promise.swift */, + DFFF6310B8F8C445362FF33E936F85CA /* Error.swift */, + 955F5499BB7496155FBF443B524F1D50 /* hang.m */, + E3B8EDBFFE2A701981A073412ECCF6AD /* join.m */, + BED547C24FF8AE5F91ED94E3BC8052C8 /* join.swift */, + 2E9E05F82273A09FD6E5CA99FD3A74D9 /* NSError+Cancellation.h */, + DDB573F3C977C55072704AA24EC06164 /* Promise.swift */, + B225BF6ADAA247F1300081D25732B5B4 /* Promise+Properties.swift */, + 1AAED38B682D186542DC2B8D273486F4 /* PromiseKit.h */, + 3EC07412ABFB8D5A06E7B38380FFD9C4 /* race.swift */, + 3BEE20F7C5242E616D2D97B5FBE31323 /* State.swift */, + B0B08C036B6283A3D528F1FBBEEF40EC /* Umbrella.h */, + 0E339112CF5C9275CFBEB94C29AD250B /* URLDataPromise.swift */, + 9C307C0A58A490D3080DB4C1E745C973 /* when.m */, + DEFA2BBF978F33CA2112DC5D6209A3EF /* when.swift */, ); - name = "Support Files"; - path = "../Target Support Files/PromiseKit"; + name = CorePromise; sourceTree = ""; }; - 83C3888E1F7B1FC86D9CBF3B74DC2896 /* QuartzCore */ = { + 79A7166061336F6A7FF214DB285A9584 /* Foundation */ = { isa = PBXGroup; children = ( - 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */, - 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */, + 178262A3EEE3B9A6F7B9B2B4ED5AA150 /* afterlife.swift */, + EFC77A5BCF407679FAB606F03E631A11 /* NSNotificationCenter+AnyPromise.h */, + DCBC249F9443D7D79A42B5C4BAC874C8 /* NSNotificationCenter+AnyPromise.m */, + 786AAA1F62613C489FD473D4CE16127A /* NSNotificationCenter+Promise.swift */, + 6650152803DA41F52DA6A26B5DF713D7 /* NSObject+Promise.swift */, + E0B0C8D6D1D56B95983D680363E6F785 /* NSURLConnection+AnyPromise.h */, + D9A940E08D42AC7D07C6B74D3310C69A /* NSURLConnection+AnyPromise.m */, + 9066E09FAD7A3236DAD81317C1E48214 /* NSURLConnection+Promise.swift */, + 5A5AEB5CADDFFFC419A0D8D6FD914800 /* NSURLSession+Promise.swift */, + ); + name = Foundation; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + E85F5154C248966A1EC7B7B6EACB20CF /* Frameworks */, + 27098387544928716460DD8F5024EE8A /* Pods */, + 01A9CB10E1E9A90B6A796034AF093E8C /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, ); - name = QuartzCore; sourceTree = ""; }; 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { @@ -490,26 +558,6 @@ path = "Target Support Files/Pods-SwaggerClient"; sourceTree = ""; }; - 8EA2A359F1831ACBB15BAAEA04D6FB95 /* UIKit */ = { - isa = PBXGroup; - children = ( - C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */, - 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */, - 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */, - FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */, - 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */, - F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */, - CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */, - BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */, - 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */, - E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */, - 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */, - AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */, - D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */, - ); - name = UIKit; - sourceTree = ""; - }; 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { isa = PBXGroup; children = ( @@ -524,66 +572,63 @@ path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; sourceTree = ""; }; - 8FCF5C41226503429E7875DF4CA4D36E /* FormURLEncode */ = { + 933F0A2EBD44D53190D1E9FAF3F54AFB /* UIKit */ = { isa = PBXGroup; children = ( - 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */, - 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */, + 0608A7843513940A299A88D778388F9D /* PMKAlertController.swift */, + 590BCD68D24A72708312E57A91360AC7 /* UIActionSheet+AnyPromise.h */, + CABB6C822D84DC5F0596B6D7B60CC5AA /* UIActionSheet+AnyPromise.m */, + DDDBF73F440D96AB666A6418AEEF2946 /* UIActionSheet+Promise.swift */, + 4E19A7D44620C4AED963248648938767 /* UIAlertView+AnyPromise.h */, + 9FB7C011EC5C968D7A91E71A028913B7 /* UIAlertView+AnyPromise.m */, + 8E29EB54AEC61300AD412C40991FFED5 /* UIAlertView+Promise.swift */, + 13DB7D7990FD3354E34510894CC30CD1 /* UIView+AnyPromise.h */, + EA13BF2FADA101A1AB34BF5EC8C7BA85 /* UIView+AnyPromise.m */, + 5E69FDAAF09817F0BA67D7C575BAFF48 /* UIView+Promise.swift */, + 7B892AF5EA37A5C7962FEA3E294B2526 /* UIViewController+AnyPromise.h */, + 53F1201EF49979297542207D6EB6EC55 /* UIViewController+AnyPromise.m */, + B7C40ADE30634419CED97EC829EE5D2C /* UIViewController+Promise.swift */, ); - name = FormURLEncode; + name = UIKit; sourceTree = ""; }; - 99640BFBD45FFAD70A89B868F85EFA36 /* Alamofire */ = { + 9466970616DD9491B9B80845EBAF6997 /* RQ */ = { isa = PBXGroup; children = ( - 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */, - A04177B09D9596450D827FE49A36C4C4 /* Download.swift */, - 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */, - 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */, - 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */, - 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */, - 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */, - 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */, - FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */, - 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */, - 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */, - 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */, - CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */, - CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */, - 9E101A4CE6D982647EED5C067C563BED /* Support Files */, + 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */, + 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */, ); - path = Alamofire; + name = RQ; sourceTree = ""; }; - 9E101A4CE6D982647EED5C067C563BED /* Support Files */ = { + 977CD7DB18C38452FB8DCFCEC690CBDE /* Support Files */ = { isa = PBXGroup; children = ( - 8749F40CC17CE0C26C36B0F431A9C8F0 /* Alamofire.modulemap */, - 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */, - 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */, - 3950B63B8EB1B9CD8FC31CDA8CC2E7C7 /* Alamofire-prefix.pch */, - 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */, - 3CE589B7B1FE57084403D25DC49528B5 /* Info.plist */, + 94F9363EEBC7855FA6B9A6B7485D5170 /* Info.plist */, + D3A577E7C7DF4A2157D9001CA0D40A72 /* PromiseKit.modulemap */, + 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */, + B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */, + 11683764D40FE241FCEEB379EE92E817 /* PromiseKit-prefix.pch */, ); name = "Support Files"; - path = "../Target Support Files/Alamofire"; + path = "../Target Support Files/PromiseKit"; sourceTree = ""; }; - A00A425F2E132E8FF4DE929E7DF9CC1E /* RQ */ = { + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { isa = PBXGroup; children = ( - 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */, - 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */, + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, ); - name = RQ; + path = Classes; sourceTree = ""; }; - AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { + B00B1E51F2524127FFF78DB52869057E /* FormURLEncode */ = { isa = PBXGroup; children = ( - F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, + 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */, + 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */, ); - path = Classes; + name = FormURLEncode; sourceTree = ""; }; B4A5C9FBC309EB945E2E089539878931 /* iOS */ = { @@ -596,34 +641,6 @@ name = iOS; sourceTree = ""; }; - BEACE1971060500B96701CBC3F667BAE /* CorePromise */ = { - isa = PBXGroup; - children = ( - B868468092D7B2489B889A50981C9247 /* after.m */, - 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */, - 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */, - 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */, - 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */, - A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */, - 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */, - 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */, - F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */, - 6AD59903FAA8315AD0036AC459FFB97F /* join.m */, - 84319E048FE6DD89B905FA3A81005C5F /* join.swift */, - 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */, - 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */, - 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */, - 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */, - 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */, - 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */, - 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */, - E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */, - 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */, - 16730DAF3E51C161D8247E473F069E71 /* when.swift */, - ); - name = CorePromise; - sourceTree = ""; - }; C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { isa = PBXGroup; children = ( @@ -633,16 +650,6 @@ name = "Targets Support Files"; sourceTree = ""; }; - CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */ = { - isa = PBXGroup; - children = ( - 99640BFBD45FFAD70A89B868F85EFA36 /* Alamofire */, - 7DFF028D9F7D443B2361EBEDACC99624 /* OMGHTTPURLRQ */, - D9FC474F1DB94FC75B3AAC120F0D4AB7 /* PromiseKit */, - ); - name = Pods; - sourceTree = ""; - }; D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { isa = PBXGroup; children = ( @@ -661,16 +668,18 @@ path = "Target Support Files/Pods-SwaggerClientTests"; sourceTree = ""; }; - D9FC474F1DB94FC75B3AAC120F0D4AB7 /* PromiseKit */ = { + DFFDACE0170FB00C7ECFDA52A87A7665 /* Support Files */ = { isa = PBXGroup; children = ( - BEACE1971060500B96701CBC3F667BAE /* CorePromise */, - 76DC20E0A9F8CDC0E47176B58A9C5BD5 /* Foundation */, - 83C3888E1F7B1FC86D9CBF3B74DC2896 /* QuartzCore */, - 81B1E3A8E00502B38EACDE3617A7A73B /* Support Files */, - 8EA2A359F1831ACBB15BAAEA04D6FB95 /* UIKit */, + 467F288FF1A023115720F192FD4D9297 /* Alamofire.modulemap */, + 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */, + F0962CCF21BDD2EB5751C14F9322AFC9 /* Alamofire-dummy.m */, + 835E52C658674D7A44ED95B966432726 /* Alamofire-prefix.pch */, + 791F2A99A7894F88F8BBAE2F6C627522 /* Alamofire-umbrella.h */, + BDEAF9E48610133B23BB992381D0E22B /* Info.plist */, ); - path = PromiseKit; + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { @@ -763,22 +772,22 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { + 8EC2461DE4442A7991319873E6012164 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, + 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */, + 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */, + 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */, + 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 8EC2461DE4442A7991319873E6012164 /* Headers */ = { + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */, - 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */, - 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */, - 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */, + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -868,38 +877,38 @@ productReference = FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */; productType = "com.apple.product-type.framework"; }; - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; buildPhases = ( - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */, - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */, - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */, + 0529825EC79AED06C77091DC0F061854 /* Sources */, + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, + FF84DA06E91FBBAA756A7832375803CE /* Headers */, ); buildRules = ( ); dependencies = ( ); - name = Alamofire; - productName = Alamofire; - productReference = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */; productType = "com.apple.product-type.framework"; }; - 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { isa = PBXNativeTarget; - buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - 0529825EC79AED06C77091DC0F061854 /* Sources */, - FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, - FF84DA06E91FBBAA756A7832375803CE /* Headers */, + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, ); buildRules = ( ); dependencies = ( ); - name = "Pods-SwaggerClientTests"; - productName = "Pods-SwaggerClientTests"; - productReference = FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */; + name = Alamofire; + productName = Alamofire; + productReference = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ @@ -923,7 +932,7 @@ projectDirPath = ""; projectRoot = ""; targets = ( - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */, 2FD913B4E24277823983BABFDB071664 /* PetstoreClient */, 1EABA30CF432461C9C71EFB7319C5EC0 /* Pods-SwaggerClient */, @@ -1024,25 +1033,28 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */, - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */, - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */, - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */, - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */, - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */, - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */, - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */, - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */, - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */, - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */, - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */, - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */, - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */, - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */, + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1082,13 +1094,13 @@ FC9E3FF49D9B636B2925749B2D51A5D3 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 4BED27A854EA6600536518D29BBB3670 /* PBXContainerItemProxy */; }; FFAF754843564CB3D6F424CE47B71A27 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 8E08EC4F5A85093B738D80C4F04BA3F1 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -1157,9 +1169,38 @@ }; name = Debug; }; + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; 6D58F928D13C57FA81A386B6364889AA /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; + baseConfigurationReference = 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1186,6 +1227,36 @@ }; name = Release; }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; 7EA02FDF9D26C9AD275654E73F406F04 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; @@ -1290,38 +1361,9 @@ }; name = Debug; }; - 9B26D3A39011247999C097562A550399 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; A1075551063662DDB4B1D70BD9D48C6E /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; + baseConfigurationReference = E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1384,7 +1426,7 @@ }; AF5D8A65BDA6B725A14D20EC25949CE0 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; + baseConfigurationReference = 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1412,36 +1454,6 @@ }; name = Debug; }; - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; F594C655D48020EC34B00AA63E001773 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1482,7 +1494,7 @@ }; F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; + baseConfigurationReference = E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1572,20 +1584,20 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 620A8F6BEDF449F55F08EDB4CDBF60A2 /* Build configuration list for PBXNativeTarget "OMGHTTPURLRQ" */ = { + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */, - A1075551063662DDB4B1D70BD9D48C6E /* Release */, + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 620A8F6BEDF449F55F08EDB4CDBF60A2 /* Build configuration list for PBXNativeTarget "OMGHTTPURLRQ" */ = { isa = XCConfigurationList; buildConfigurations = ( - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, - 9B26D3A39011247999C097562A550399 /* Release */, + F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */, + A1075551063662DDB4B1D70BD9D48C6E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift index 06d5aa5c825..fa52fbf2f25 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift @@ -6,7 +6,7 @@ import PromiseKit /** @return A promise that resolves when the provided object deallocates - @warning *Important* The promise is not guarenteed to resolve immediately + @warning *Important* The promise is not guaranteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing. */ diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h index b131488df70..f36a07658b9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h @@ -77,7 +77,7 @@ @interface UIViewController (PMKUnavailable) #define PMKRationale \ - "The promiseViewController system has been rennovated: the fullfil and " \ + "The promiseViewController system has been renovated: the fullfil and " \ "reject category methods have been removed due to runtime safety " \ "concerns and instead you should implement a -promise property on your " \ "view controller subclass. @see promiseViewController:animated:completion:" diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown index 84aabe138db..8fee72c0d70 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown @@ -22,7 +22,7 @@ PromiseKit is a thoughtful and complete implementation of promises for iOS and O # Which PromiseKit Should I Use? -If you are writing a library, [**use PromiseKit 1.x**](https://github.com/mxcl/PromiseKit/tree/legacy-1.x). This is because PromiseKit > 2 breaks everytime Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates. +If you are writing a library, [**use PromiseKit 1.x**](https://github.com/mxcl/PromiseKit/tree/legacy-1.x). This is because PromiseKit > 2 breaks every time Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates. If you are making an app then PromiseKit 3 is the best PromiseKit, you may have to make some fixes when Xcode updates, but probably you will be OK as long as you update PromiseKit when Xcode updates. @@ -35,7 +35,7 @@ Thus we intend to support PromiseKit 1.x for longer than expected. # PromiseKit 3 -In Swift 2.0 `catch` and `defer` became reserved keywords mandating we rename our functions with these names. This forced a major semantic version change on PromiseKit and thus we took the opportunity to make other minor (source compatability breaking) improvements. +In Swift 2.0 `catch` and `defer` became reserved keywords mandating we rename our functions with these names. This forced a major semantic version change on PromiseKit and thus we took the opportunity to make other minor (source compatibility breaking) improvements. Thus if you cannot afford to adapt to PromiseKit 3 but still want to use Xcode-7.0/Swift-2.0 we provide a [minimal changes branch] where `catch` and `defer` are renamed `catch_` and `defer_` and all other changes are the bare minimum to make PromiseKit 2 compile against Swift 2. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h index 5a76d4d7147..b76075f3f73 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h @@ -75,7 +75,7 @@ typedef NS_ENUM(NSInteger, PMKCatchPolicy) { @warning *Note* Cancellation errors are not caught. - @warning *Note* Since catch is a c++ keyword, this method is not availble in Objective-C++ files. Instead use catchWithPolicy. + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchWithPolicy. @see catchWithPolicy */ @@ -126,7 +126,7 @@ typedef NS_ENUM(NSInteger, PMKCatchPolicy) { /** Creates a resolved promise. - When developing your own promise systems, it is ocassionally useful to be able to return an already resolved promise. + When developing your own promise systems, it is occasionally useful to be able to return an already resolved promise. @param value The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, otherwise the promise will be fulfilled. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift index 477d1109bb1..96e2cd3ba79 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift @@ -47,7 +47,7 @@ public class Promise { } - Parameter resolvers: The provided closure is called immediately. - Inside, execute your asynchronous system, calling fulfill if it suceeds + Inside, execute your asynchronous system, calling fulfill if it succeeds and reject for any errors. - Returns: return A new promise. @@ -532,7 +532,7 @@ public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil) then is going to take a while and doesn’t interact with the UI. Please note (again) that generally you should not use zalgo or waldo. The - performance gains are neglible and we provide these functions only out of + performance gains are negligible and we provide these functions only out of a misguided sense that library code should be as optimized as possible. If you use zalgo or waldo without tests proving their correctness you may unwillingly introduce horrendous, near-impossible-to-trace bugs. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist index c1aea25c248..7694605fe7a 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.5 + 3.4.1 CFBundleSignature ???? CFBundleVersion diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist index 793d31a9fdd..8b511bb3946 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.1 + 3.1.3 CFBundleSignature ???? CFBundleVersion diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown index 876c8ce5ee8..e6778cdc3f6 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## Alamofire -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,7 +26,7 @@ THE SOFTWARE. ## OMGHTTPURLRQ -See README.markdown for full license text. +https://github.com/mxcl/OMGHTTPURLRQ/blob/master/README.markdown ## PetstoreClient diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist index 49af015bfaf..dfbd5e635c9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -41,7 +41,7 @@ THE SOFTWARE. FooterText - See README.markdown for full license text. + https://github.com/mxcl/OMGHTTPURLRQ/blob/master/README.markdown Title OMGHTTPURLRQ Type diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 3d557a9280f..0eec9dcf8c6 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -143,12 +143,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -163,12 +163,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -239,14 +239,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -254,14 +254,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -269,14 +269,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -284,14 +284,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -299,14 +299,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -314,14 +314,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index c5f9750c8bf..e76c5700aa2 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -61,22 +61,8 @@ class PetAPITests: XCTestCase { func test3DeletePet() { let expectation = self.expectationWithDescription("testDeletePet") - PetAPI.deletePet(petId: 1000).always { - // expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { - expectation.fulfill() - } else { - XCTFail("error logging out") - } + PetAPI.deletePet(petId: 1000).then { + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index b52fe4a0fa8..2e37e3d3917 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -12,26 +12,19 @@ import XCTest @testable import SwaggerClient class StoreAPITests: XCTestCase { - - let testTimeout = 10.0 - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } + let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + + let testTimeout = 10.0 func test1PlaceOrder() { let order = Order() + let shipDate = NSDate() order.id = 1000 order.petId = 1000 order.complete = false order.quantity = 10 - order.shipDate = NSDate() + order.shipDate = shipDate // use explicit naming to reference the enum so that we test we don't regress on enum naming order.status = Order.Status.Placed let expectation = self.expectationWithDescription("testPlaceOrder") @@ -39,6 +32,9 @@ class StoreAPITests: XCTestCase { XCTAssert(order.id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .Placed, "invalid status") + XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), + "Date should be idempotent") + expectation.fulfill() }.always { // Noop for now @@ -66,23 +62,27 @@ class StoreAPITests: XCTestCase { func test3DeleteOrder() { let expectation = self.expectationWithDescription("testDeleteOrder") StoreAPI.deleteOrder(orderId: "1000").then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { - expectation.fulfill() - } else { - XCTFail("error deleting order") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } } + +private extension NSDate { + + /** + Returns true if the dates are equal given the format string. + + - parameter date: The date to compare to. + - parameter format: The format string to use to compare. + + - returns: true if the dates are equal, given the format string. + */ + func isEqual(date: NSDate, format: String) -> Bool { + let fmt = NSDateFormatter() + fmt.dateFormat = format + return fmt.stringFromDate(self).isEqual(fmt.stringFromDate(date)) + } + +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 7129ecd226a..2caacc8d6da 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -14,34 +14,11 @@ import XCTest class UserAPITests: XCTestCase { let testTimeout = 10.0 - - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - + func testLogin() { let expectation = self.expectationWithDescription("testLogin") UserAPI.loginUser(username: "swiftTester", password: "swift").then { _ -> Void in expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server isn't returning JSON - and currently the alamofire implementation - // always parses responses as JSON, so making an exception for this here - // Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." - // UserInfo={NSDebugDescription=Invalid value around character 0.} - let error = errorType as NSError - if error.code == 3840 { - expectation.fulfill() - } else { - XCTFail("error logging in") - } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } @@ -49,21 +26,7 @@ class UserAPITests: XCTestCase { func testLogout() { let expectation = self.expectationWithDescription("testLogout") UserAPI.logoutUser().then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { - expectation.fulfill() - } else { - XCTFail("error logging out") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } @@ -80,21 +43,7 @@ class UserAPITests: XCTestCase { newUser.username = "test@test.com" newUser.userStatus = 0 UserAPI.createUser(body: newUser).then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { - expectation.fulfill() - } else { - XCTFail("error creating user") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } @@ -120,21 +69,7 @@ class UserAPITests: XCTestCase { func test3DeleteUser() { let expectation = self.expectationWithDescription("testDeleteUser") UserAPI.deleteUser(username: "test@test.com").then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { - expectation.fulfill() - } else { - XCTFail("error logging out") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift/rxswift/.gitignore b/samples/client/petstore/swift/rxswift/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/.gitignore @@ -0,0 +1,63 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore/swift/rxswift/.swagger-codegen-ignore b/samples/client/petstore/swift/rxswift/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/.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/swift/rxswift/Cartfile b/samples/client/petstore/swift/rxswift/Cartfile new file mode 100644 index 00000000000..d862ef91d09 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/Cartfile @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 3.1.0 +github "ReactiveX/RxSwift" ~> 2.0 diff --git a/samples/client/petstore/swift/rxswift/LICENSE b/samples/client/petstore/swift/rxswift/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient.podspec b/samples/client/petstore/swift/rxswift/PetstoreClient.podspec new file mode 100644 index 00000000000..422a88b3c00 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient.podspec @@ -0,0 +1,14 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Apache License, Version 2.0' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'RxSwift', '~> 2.0' + s.dependency 'Alamofire', '~> 3.4.1' +end diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..23e727b6b54 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,40 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..ab0ea147e4f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,76 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public class PetstoreClientAPI { + public static var basePath = "http://petstore.swagger.io/v2" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +public class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in (encoded as! [AnyObject]).enumerate() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +public class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + + addHeaders(PetstoreClientAPI.customHeaders) + } + + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } + + public func addHeader(name name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + public func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 00000000000..a38dabd888f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,608 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import RxSwift + + + +public class PetAPI: APIBase { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func addPet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - returns: Observable + */ + public class func addPet(body body: Pet? = nil) -> Observable { + return Observable.create { observer -> Disposable in + addPet(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Add a new pet to the store + - POST /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store (optional) + + - returns: RequestBuilder + */ + public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) { + deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - returns: Observable + */ + public class func deletePet(petId petId: Int64) -> Observable { + return Observable.create { observer -> Disposable in + deletePet(petId: petId) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) Pet id to delete + + - returns: RequestBuilder + */ + public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + - returns: Observable<[Pet]> + */ + public class func findPetsByStatus(status status: [String]? = nil) -> Observable<[Pet]> { + return Observable.create { observer -> Disposable in + findPetsByStatus(status: status) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + 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/json, example={ + "name" : "Puma", + "type" : "Dog", + "color" : "Black", + "gender" : "Female", + "breed" : "Mixed" +}}] + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "status": status + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by (optional) + - returns: Observable<[Pet]> + */ + public class func findPetsByTags(tags tags: [String]? = nil) -> Observable<[Pet]> { + return Observable.create { observer -> Disposable in + findPetsByTags(tags: tags) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + 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/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + + - parameter tags: (query) Tags to filter by (optional) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "tags": tags + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet that needs to be fetched + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet that needs to be fetched + - returns: Observable + */ + public class func getPetById(petId petId: Int64) -> Observable { + return Observable.create { observer -> Disposable in + getPetById(petId: petId) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + - OAuth: + - type: oauth2 + - name: petstore_auth + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + + - parameter petId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - returns: Observable + */ + public class func updatePet(body body: Pet? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updatePet(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Update an existing pet + - PUT /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store (optional) + + - returns: RequestBuilder + */ + public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Updates a pet in the store with form data + + - 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: Observable + */ + public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updatePetWithForm(petId: petId, name: name, status: status) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + + - returns: RequestBuilder + */ + public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "name": name, + "status": status + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + uploads an image + + - 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: Observable + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> Observable { + return Observable.create { observer -> Disposable in + uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + + - returns: RequestBuilder + */ + public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 00000000000..6e5d88db1e1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,302 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import RxSwift + + + +public class StoreAPI: APIBase { + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: Observable + */ + public class func deleteOrder(orderId orderId: String) -> Observable { + return Observable.create { observer -> Disposable in + deleteOrder(orderId: orderId) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Delete purchase order by ID + - DELETE /store/order/{orderId} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + - parameter orderId: (path) ID of the order that needs to be deleted + + - returns: RequestBuilder + */ + public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Returns pet inventories by status + + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Returns pet inventories by status + + - returns: Observable<[String:Int32]> + */ + public class func getInventory() -> Observable<[String:Int32]> { + return Observable.create { observer -> Disposable in + getInventory() { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "key" : 123 +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ + "key" : 123 +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + + - returns: RequestBuilder<[String:Int32]> + */ + public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: Observable + */ + public class func getOrderById(orderId orderId: String) -> Observable { + return Observable.create { observer -> Disposable in + getOrderById(orderId: orderId) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Find purchase order by ID + - GET /store/order/{orderId} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func placeOrder(body body: Order? = nil, completion: ((data: Order?, error: ErrorType?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet (optional) + - returns: Observable + */ + public class func placeOrder(body body: Order? = nil) -> Observable { + return Observable.create { observer -> Disposable in + placeOrder(body: body) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Place an order for a pet + - POST /store/order + - + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + + - parameter body: (body) order placed for purchasing the pet (optional) + + - returns: RequestBuilder + */ + public class func placeOrderWithRequestBuilder(body body: Order? = nil) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 00000000000..0dbc4e7b340 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,498 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import RxSwift + + + +public class UserAPI: APIBase { + /** + Create user + + - parameter body: (body) Created user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUser(body body: User? = nil, completion: ((error: ErrorType?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Create user + + - parameter body: (body) Created user object (optional) + - returns: Observable + */ + public class func createUser(body body: User? = nil) -> Observable { + return Observable.create { observer -> Disposable in + createUser(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object (optional) + + - returns: RequestBuilder + */ + public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUsersWithArrayInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - returns: Observable + */ + public class func createUsersWithArrayInput(body body: [User]? = nil) -> Observable { + return Observable.create { observer -> Disposable in + createUsersWithArrayInput(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object (optional) + + - returns: RequestBuilder + */ + public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUsersWithListInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - returns: Observable + */ + public class func createUsersWithListInput(body body: [User]? = nil) -> Observable { + return Observable.create { observer -> Disposable in + createUsersWithListInput(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object (optional) + + - returns: RequestBuilder + */ + public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - returns: Observable + */ + public class func deleteUser(username username: String) -> Observable { + return Observable.create { observer -> Disposable in + deleteUser(username: username) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) The name that needs to be deleted + + - returns: RequestBuilder + */ + public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: Observable + */ + public class func getUserByName(username username: String) -> Observable { + return Observable.create { observer -> Disposable in + getUserByName(username: username) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Get user by user name + - GET /user/{username} + - + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + string + string + string + string + string + string + 0 +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + string + string + string + string + string + string + 0 +}] + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + + - returns: RequestBuilder + */ + public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + - returns: Observable + */ + public class func loginUser(username username: String? = nil, password: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + loginUser(username: username, password: password) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Logs user into the system + - GET /user/login + - + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + + - returns: RequestBuilder + */ + public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "username": username, + "password": password + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Logs out current logged in user session + + - parameter completion: completion handler to receive the data and the error objects + */ + public class func logoutUser(completion: ((error: ErrorType?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Logs out current logged in user session + + - returns: Observable + */ + public class func logoutUser() -> Observable { + return Observable.create { observer -> Disposable in + logoutUser() { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + public class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updateUser(username username: String, body: User? = nil, completion: ((error: ErrorType?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + - returns: Observable + */ + public class func updateUser(username username: String, body: User? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updateUser(username: username, body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + + - returns: RequestBuilder + */ + public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..4ea47d8926c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,213 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +public struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = dispatch_queue_create("SynchronizedDictionary", DISPATCH_QUEUE_CONCURRENT) + + public subscript(key: K) -> V? { + get { + var value: V? + + dispatch_sync(queue) { + value = self.dictionary[key] + } + + return value + } + + set { + dispatch_barrier_sync(queue) { + self.dictionary[key] = newValue + } + } + } + +} + +// Store manager to retain its reference +private var managerStore = SynchronizedDictionary() + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) + } + } + ) + } else { + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> 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( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) + case is NSData.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) + } + } + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..c974cc40b36 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,86 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(int: self) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} + +private let dateFormatter: NSDateFormatter = { + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} + +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + + diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..32175b605a3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,228 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T? + + public init(statusCode: Int, header: [String: String], body: T?) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: NSHTTPURLResponse, body: T?) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictionary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { + initialize() + if T.self is Int32.Type && source is NSNumber { + return source.intValue as! T; + } + if T.self is Int64.Type && source is NSNumber { + return source.longLongValue as! T; + } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } + if source is T { + return source as! T + } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + + } + if let sourceInt = source as? Int { + // treat as a java date + return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) ) + } + fatalError("formatter failed to parse \(source)") + } + + // Decoder for [Category] + Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in + return Decoders.decode(clazz: [Category].self, source: source) + } + // Decoder for Category + Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Category() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [Order] + Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in + return Decoders.decode(clazz: [Order].self, source: source) + } + // Decoder for Order + Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Order() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"]) + instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"]) + instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) + instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) + return instance + } + + + // Decoder for [Pet] + Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in + return Decoders.decode(clazz: [Pet].self, source: source) + } + // Decoder for Pet + Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Pet() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) + instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) + instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + return instance + } + + + // Decoder for [Tag] + Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in + return Decoders.decode(clazz: [Tag].self, source: source) + } + // Decoder for Tag + Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Tag() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [User] + Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in + return Decoders.decode(clazz: [User].self, source: source) + } + // Decoder for User + Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = User() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"]) + instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"]) + instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"]) + instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"]) + instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"]) + instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"]) + instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"]) + return instance + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 00000000000..89ce2ccb616 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,25 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Category: JSONEncodable { + public var id: Int64? + public var name: String? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 00000000000..87b2a2c5247 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,39 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Order: JSONEncodable { + public enum Status: String { + case Placed = "placed" + case Approved = "approved" + case Delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? + public var shipDate: NSDate? + /** Order Status */ + public var status: Status? + public var complete: Bool? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["petId"] = self.petId?.encodeToJSON() + nillableDictionary["quantity"] = self.quantity?.encodeToJSON() + nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + nillableDictionary["complete"] = self.complete + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 00000000000..ebcd2c1825f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,39 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Pet: JSONEncodable { + public enum Status: String { + case Available = "available" + case Pending = "pending" + case Sold = "sold" + } + public var id: Int64? + public var category: Category? + public var name: String? + public var photoUrls: [String]? + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["category"] = self.category?.encodeToJSON() + nillableDictionary["name"] = self.name + nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON() + nillableDictionary["tags"] = self.tags?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 00000000000..774f91557e6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,25 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Tag: JSONEncodable { + public var id: Int64? + public var name: String? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 00000000000..67b72a61922 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,38 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class User: JSONEncodable { + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int32? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["username"] = self.username + nillableDictionary["firstName"] = self.firstName + nillableDictionary["lastName"] = self.lastName + nillableDictionary["email"] = self.email + nillableDictionary["password"] = self.password + nillableDictionary["phone"] = self.phone + nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile new file mode 100644 index 00000000000..29843508b65 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile @@ -0,0 +1,10 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE new file mode 100644 index 00000000000..4cfbf72a4d8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md new file mode 100644 index 00000000000..e0acf722db1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md @@ -0,0 +1,1297 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) + +Alamofire is an HTTP networking library written in Swift. + +## Features + +- [x] Chainable Request / Response methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download using Request or Resume data +- [x] Authentication with NSURLCredential +- [x] HTTP Response Validation +- [x] TLS Certificate and Public Key Pinning +- [x] Progress Closure & NSProgress +- [x] cURL Debug Output +- [x] Comprehensive Unit Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 7.3+ + +## Migration Guides + +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).** +> +> Alamofire is no longer supported on iOS 7 due to the lack of support for frameworks. Without frameworks, running Travis-CI against iOS 7 would require a second duplicated test target. The separate test suite would need to import all the Swift files and the tests would need to be duplicated and re-written. This split would be too difficult to maintain to ensure the highest possible quality of the Alamofire ecosystem. + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '9.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 3.4' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 3.4 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + +```bash +$ git init +``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + +```bash +$ git submodule add https://github.com/Alamofire/Alamofire.git +``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS` or `Alamofire OSX`. + +- And that's it! + +> The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +### Response Handling + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .responseJSON { response in + print(response.request) // original URL request + print(response.response) // URL response + print(response.data) // server data + print(response.result) // result of response serialization + + if let JSON = response.result.value { + print("JSON: \(JSON)") + } + } +``` + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. + +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + +### Response Serialization + +**Built-in Response Methods** + +- `response()` +- `responseData()` +- `responseString(encoding: NSStringEncoding)` +- `responseJSON(options: NSJSONReadingOptions)` +- `responsePropertyList(options: NSPropertyListReadOptions)` + +#### Response Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .response { request, response, data, error in + print(request) + print(response) + print(data) + print(error) + } +``` + +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseData { response in + print(response.request) + print(response.response) + print(response.result) + } +``` + +#### Response String Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .validate() + .responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") + } +``` + +#### Response JSON Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .validate() + .responseJSON { response in + debugPrint(response) + } +``` + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .validate() + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +### HTTP Methods + +`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} +``` + +These values can be passed as the first argument of the `Alamofire.request` method: + +```swift +Alamofire.request(.POST, "https://httpbin.org/post") + +Alamofire.request(.PUT, "https://httpbin.org/put") + +Alamofire.request(.DELETE, "https://httpbin.org/delete") +``` + +### Parameters + +#### GET Request With URL-Encoded Parameters + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) +// https://httpbin.org/get?foo=bar +``` + +#### POST Request With URL-Encoded Parameters + +```swift +let parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters) +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +### Parameter Encoding + +Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum: + +```swift +enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) + { ... } +} +``` + +- `URL`: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. _Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`)._ +- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. +- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. +- `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. + +#### Manual Parameter Encoding of an NSURLRequest + +```swift +let URL = NSURL(string: "https://httpbin.org/get")! +var request = NSMutableURLRequest(URL: URL) + +let parameters = ["foo": "bar"] +let encoding = Alamofire.ParameterEncoding.URL +(request, _) = encoding.encode(request, parameters: parameters) +``` + +#### POST Request with JSON-encoded Parameters + +```swift +let parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON) +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +> For HTTP headers that do not change, it is recommended to set them on the `NSURLSessionConfiguration` so they are automatically applied to any `NSURLSessionTask` created by the underlying `NSURLSession`. + +```swift +let headers = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Accept": "application/json" +] + +Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +### Caching + +Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache). + +### Uploading + +**Supported Upload Types** + +- File +- Data +- Stream +- MultipartFormData + +#### Uploading a File + +```swift +let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png") +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) +``` + +#### Uploading with Progress + +```swift +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) + .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in + print(totalBytesWritten) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes written on main queue: \(totalBytesWritten)") + } + } + .validate() + .responseJSON { response in + debugPrint(response) + } +``` + +#### Uploading MultipartFormData + +```swift +Alamofire.upload( + .POST, + "https://httpbin.org/post", + multipartFormData: { multipartFormData in + multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn") + multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow") + }, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .Failure(let encodingError): + print(encodingError) + } + } +) +``` + +### Downloading + +**Supported Download Types** + +- Request +- Resume Data + +#### Downloading a File + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in + let fileManager = NSFileManager.defaultManager() + let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] + let pathComponent = response.suggestedFilename + + return directoryURL.URLByAppendingPathComponent(pathComponent!) +} +``` + +#### Using the Default Download Destination + +```swift +let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +``` + +#### Downloading a File w/Progress + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in + print(totalBytesRead) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes read on main queue: \(totalBytesRead)") + } + } + .response { _, _, _, error in + if let error = error { + print("Failed with error: \(error)") + } else { + print("Downloaded file successfully") + } + } +``` + +#### Accessing Resume Data for Failed Downloads + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .response { _, _, data, _ in + if let + data = data, + resumeDataString = NSString(data: data, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } + } +``` + +> The `data` parameter is automatically populated with the `resumeData` if available. + +```swift +let download = Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +download.response { _, _, _, _ in + if let + resumeData = download.resumeData, + resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } +} +``` + +### Authentication + +Authentication is handled on the system framework level by [`NSURLCredential` and `NSURLAuthenticationChallenge`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! +let base64Credentials = credentialData.base64EncodedStringWithOptions([]) + +let headers = ["Authorization": "Basic \(base64Credentials)"] + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with NSURLCredential + +```swift +let user = "user" +let password = "password" + +let credential = NSURLCredential(user: user, password: password, persistence: .ForSession) + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +### Timeline + +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + print(response.timeline) + } +``` + +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + +### Printable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +### DebugPrintable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + +debugPrint(request) +``` + +#### Output (cURL) + +```bash +$ curl -i \ + -H "User-Agent: Alamofire" \ + -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +> Alamofire is built on `NSURLSession` and the Foundation URL Loading System. To make the most of +this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [NSURLSession Class Reference](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/Introduction/Introduction.html#//apple_ref/occ/cl/NSURLSession) +- [NSURLCache Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache) +- [NSURLAuthenticationChallenge Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html) + +### Manager + +Top-level convenience methods like `Alamofire.request` use a shared instance of `Alamofire.Manager`, which is configured with the default `NSURLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +```swift +let manager = Alamofire.Manager.sharedInstance +manager.request(NSURLRequest(URL: NSURL(string: "https://httpbin.org/get")!)) +``` + +Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`HTTPAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Manager with Default Configuration + +```swift +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Background Configuration + +```swift +let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background") +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Ephemeral Configuration + +```swift +let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Modifying Session Configuration + +```swift +var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +configuration.HTTPAdditionalHeaders = defaultHeaders + +let manager = Alamofire.Manager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Request + +The result of a `request`, `upload`, or `download` method is an instance of `Alamofire.Request`. A request is always created using a constructor method from an owning manager, and never initialized directly. + +Methods like `authenticate`, `validate` and `responseData` return the caller in order to facilitate chaining. + +Requests can be suspended, resumed, and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Response Serialization + +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples: + +```swift +public enum BackendError: ErrorType { + case Network(error: NSError) + case DataSerialization(reason: String) + case JSONSerialization(error: NSError) + case ObjectSerialization(reason: String) + case XMLSerialization(error: NSError) +} +``` + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension Request { + public static func XMLResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } + + guard let validData = data else { + return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil.")) + } + + do { + let XML = try ONOXMLDocument(data: validData) + return .Success(XML) + } catch { + return .Failure(.XMLSerialization(error: error as NSError)) + } + } + } + + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +public protocol ResponseObjectSerializable { + init?(response: NSHTTPURLResponse, representation: AnyObject) +} + +extension Request { + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } + + let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONResponseSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let + response = response, + responseObject = T(response: response, representation: value) + { + return .Success(responseObject) + } else { + return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)")) + } + case .Failure(let error): + return .Failure(.JSONSerialization(error: error)) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } +} +``` + +```swift +Alamofire.request(.GET, "https://example.com/users/mattt") + .responseObject { (response: Response) in + debugPrint(response) + } +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +public protocol ResponseCollectionSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] +} + +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] { + var collection = [Self]() + + if let representation = representation as? [[String: AnyObject]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} + +extension Alamofire.Request { + public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } + + let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let response = response { + return .Success(T.collection(response: response, representation: value)) + } else { + return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response")) + } + case .Failure(let error): + return .Failure(.JSONSerialization(error: error)) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable, ResponseCollectionSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } +} +``` + +```swift +Alamofire.request(.GET, "http://example.com/users") + .responseCollection { (response: Response<[User], BackendError>) in + debugPrint(response) + } +``` + +### URLStringConvertible + +Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. `NSString`, `NSURL`, `NSURLComponents`, and `NSURLRequest` conform to `URLStringConvertible` by default, allowing any of them to be passed as `URLString` parameters to the `request`, `upload`, and `download` methods: + +```swift +let string = NSString(string: "https://httpbin.org/post") +Alamofire.request(.POST, string) + +let URL = NSURL(string: string)! +Alamofire.request(.POST, URL) + +let URLRequest = NSURLRequest(URL: URL) +Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest` + +let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) +Alamofire.request(.POST, URLComponents) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLStringConvertible` as a convenient way to map domain-specific models to server resources. + +#### Type-Safe Routing + +```swift +extension User: URLStringConvertible { + static let baseURLString = "http://example.com" + + var URLString: String { + return User.baseURLString + "/users/\(username)/" + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(.GET, user) // http://example.com/users/mattt +``` + +### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `NSURLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let URL = NSURL(string: "https://httpbin.org/post")! +let mutableURLRequest = NSMutableURLRequest(URL: URL) +mutableURLRequest.HTTPMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions()) +} catch { + // No-op +} + +mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(mutableURLRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +#### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static let perPage = 50 + + case Search(query: String, page: Int) + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let result: (path: String, parameters: [String: AnyObject]) = { + switch self { + case .Search(let query, let page) where page > 0: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case .Search(let query, _): + return ("/search", ["q": query]) + } + }() + + let URL = NSURL(string: Router.baseURLString)! + let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) + let encoding = Alamofire.ParameterEncoding.URL + + return encoding.encode(URLRequest, parameters: result.parameters).0 + } +} +``` + +```swift +Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50 +``` + +#### CRUD & Authorization + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static var OAuthToken: String? + + case CreateUser([String: AnyObject]) + case ReadUser(String) + case UpdateUser(String, [String: AnyObject]) + case DestroyUser(String) + + var method: Alamofire.Method { + switch self { + case .CreateUser: + return .POST + case .ReadUser: + return .GET + case .UpdateUser: + return .PUT + case .DestroyUser: + return .DELETE + } + } + + var path: String { + switch self { + case .CreateUser: + return "/users" + case .ReadUser(let username): + return "/users/\(username)" + case .UpdateUser(let username, _): + return "/users/\(username)" + case .DestroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let URL = NSURL(string: Router.baseURLString)! + let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) + mutableURLRequest.HTTPMethod = method.rawValue + + if let token = Router.OAuthToken { + mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + + switch self { + case .CreateUser(let parameters): + return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 + case .UpdateUser(_, let parameters): + return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 + default: + return mutableURLRequest + } + } +} +``` + +```swift +Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt +``` + +### SessionDelegate + +By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. +public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + +/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. +public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + +/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. +public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + +/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. +public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let delegate: Alamofire.Manager.SessionDelegate = manager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: Manager.SessionDelegate { + override func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.URLSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `PinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. +* `PinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. +* `DisableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. +* `CustomEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .DisableEvaluation +] + +let manager = Manager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `Manager` instance, otherwise your requests will all get cancelled when your `manager` is deallocated. + +These server trust policies will result in the following behavior: + +* `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + * Certificate chain MUST be valid. + * Certificate chain MUST include one of the pinned certificates. + * Challenge host MUST match the host in the certificate chain's leaf certificate. +* `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +* All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +### Network Reachability + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +* **Do NOT** use Reachability to determine if a network request should be sent. + * You should **ALWAYS** send it. +* When Reachability is restored, use the event to retry failed network requests. + * Even though the network requests may still fail, this is a good moment to retry them. +* The network reachability status can be useful for determining why a network request may have failed. + * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- + +## Open Rdars + +The following rdars have some affect on the current implementation of Alamofire. + +* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +* Pay our legal fees to register as a federal non-profit organization +* Pay our yearly legal fees to keep the non-profit in good status +* Pay for our mail servers to help us stay on top of all questions and security issues +* Potentially fund test servers to make it easier for us to test the edge cases +* Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 00000000000..0945204dcca --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,369 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: - URLStringConvertible + +/** + Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to + construct URL requests. +*/ +public protocol URLStringConvertible { + /** + A URL that conforms to RFC 2396. + + Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. + + See https://tools.ietf.org/html/rfc2396 + See https://tools.ietf.org/html/rfc1738 + See https://tools.ietf.org/html/rfc1808 + */ + var URLString: String { get } +} + +extension String: URLStringConvertible { + public var URLString: String { return self } +} + +extension NSURL: URLStringConvertible { + public var URLString: String { return absoluteString } +} + +extension NSURLComponents: URLStringConvertible { + public var URLString: String { return URL!.URLString } +} + +extension NSURLRequest: URLStringConvertible { + public var URLString: String { return URL!.URLString } +} + +// MARK: - URLRequestConvertible + +/** + Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +*/ +public protocol URLRequestConvertible { + /// The URL request. + var URLRequest: NSMutableURLRequest { get } +} + +extension NSURLRequest: URLRequestConvertible { + public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } +} + +// MARK: - Convenience + +func URLRequest( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil) + -> NSMutableURLRequest +{ + let mutableURLRequest: NSMutableURLRequest + + if let request = URLString as? NSMutableURLRequest { + mutableURLRequest = request + } else if let request = URLString as? NSURLRequest { + mutableURLRequest = request.URLRequest + } else { + mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) + } + + mutableURLRequest.HTTPMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) + } + } + + return mutableURLRequest +} + +// MARK: - Request Methods + +/** + Creates a request using the shared manager instance for the specified method, URL string, parameters, and + parameter encoding. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. +*/ +public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request +{ + return Manager.sharedInstance.request( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/** + Creates a request using the shared manager instance for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. +*/ +public func request(URLRequest: URLRequestConvertible) -> Request { + return Manager.sharedInstance.request(URLRequest.URLRequest) +} + +// MARK: - Upload Methods + +// MARK: File + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and file. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and file. + + - parameter URLRequest: The URL request. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return Manager.sharedInstance.upload(URLRequest, file: file) +} + +// MARK: Data + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and data. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and data. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return Manager.sharedInstance.upload(URLRequest, data: data) +} + +// MARK: Stream + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and stream. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and stream. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return Manager.sharedInstance.upload(URLRequest, stream: stream) +} + +// MARK: MultipartFormData + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + method, + URLString, + headers: headers, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + URLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +// MARK: - Download Methods + +// MARK: URL Request + +/** + Creates a download request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request +{ + return Manager.sharedInstance.download( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers, + destination: destination + ) +} + +/** + Creates a download request using the shared manager instance for the specified URL request. + + - parameter URLRequest: The URL request. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(URLRequest, destination: destination) +} + +// MARK: Resume Data + +/** + Creates a request using the shared manager instance for downloading from the resume data produced from a + previous request cancellation. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(data, destination: destination) +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift new file mode 100644 index 00000000000..52e90badfde --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -0,0 +1,248 @@ +// +// Download.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Manager { + private enum Downloadable { + case Request(NSURLRequest) + case ResumeData(NSData) + } + + private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { + var downloadTask: NSURLSessionDownloadTask! + + switch downloadable { + case .Request(let request): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithRequest(request) + } + case .ResumeData(let resumeData): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithResumeData(resumeData) + } + } + + let request = Request(session: session, task: downloadTask) + + if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { + downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in + return destination(URL, downloadTask.response as! NSHTTPURLResponse) + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: Request + + /** + Creates a download request for the specified method, URL string, parameters, parameter encoding, headers + and destination. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + + return download(encodedURLRequest, destination: destination) + } + + /** + Creates a request for downloading from the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return download(.Request(URLRequest.URLRequest), destination: destination) + } + + // MARK: Resume Data + + /** + Creates a request for downloading from the resume data produced from a previous request cancellation. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for + additional information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { + return download(.ResumeData(resumeData), destination: destination) + } +} + +// MARK: - + +extension Request { + /** + A closure executed once a request has successfully completed in order to determine where to move the temporary + file written to during the download process. The closure takes two arguments: the temporary file URL and the URL + response, and returns a single argument: the file URL where the temporary file should be moved. + */ + public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL + + /** + Creates a download file destination closure which uses the default file manager to move the temporary file to a + file URL in the first available directory with the specified search path directory and search path domain mask. + + - parameter directory: The search path directory. `.DocumentDirectory` by default. + - parameter domain: The search path domain mask. `.UserDomainMask` by default. + + - returns: A download file destination closure. + */ + public class func suggestedDownloadDestination( + directory directory: NSSearchPathDirectory = .DocumentDirectory, + domain: NSSearchPathDomainMask = .UserDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response -> NSURL in + let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) + + if !directoryURLs.isEmpty { + return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) + } + + return temporaryURL + } + } + + /// The resume data of the underlying download task if available after a failure. + public var resumeData: NSData? { + var data: NSData? + + if let delegate = delegate as? DownloadTaskDelegate { + data = delegate.resumeData + } + + return data + } + + // MARK: - DownloadTaskDelegate + + class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { + var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } + var downloadProgress: ((Int64, Int64, Int64) -> Void)? + + var resumeData: NSData? + override var data: NSData? { return resumeData } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? + var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + do { + let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) + } catch { + self.error = error as NSError + } + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift new file mode 100644 index 00000000000..467d99c916c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -0,0 +1,88 @@ +// +// Error.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. +public struct Error { + /// The domain used for creating all Alamofire errors. + public static let Domain = "com.alamofire.error" + + /// The custom error codes generated by Alamofire. + public enum Code: Int { + case InputStreamReadFailed = -6000 + case OutputStreamWriteFailed = -6001 + case ContentTypeValidationFailed = -6002 + case StatusCodeValidationFailed = -6003 + case DataSerializationFailed = -6004 + case StringSerializationFailed = -6005 + case JSONSerializationFailed = -6006 + case PropertyListSerializationFailed = -6007 + } + + /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. + public struct UserInfoKeys { + /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. + public static let ContentType = "ContentType" + + /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. + public static let StatusCode = "StatusCode" + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + @available(*, deprecated=3.4.0) + public static func errorWithCode(code: Code, failureReason: String) -> NSError { + return errorWithCode(code.rawValue, failureReason: failureReason) + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + @available(*, deprecated=3.4.0) + public static func errorWithCode(code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: Domain, code: code, userInfo: userInfo) + } + + static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { + return error(domain: domain, code: code.rawValue, failureReason: failureReason) + } + + static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: domain, code: code, userInfo: userInfo) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift new file mode 100644 index 00000000000..cbfb5c77bff --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -0,0 +1,779 @@ +// +// Manager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/** + Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +*/ +public class Manager { + + // MARK: - Properties + + /** + A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly + for any ad hoc requests. + */ + public static let sharedInstance: Manager = { + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders + + return Manager(configuration: configuration) + }() + + /** + Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + */ + public static let defaultHTTPHeaders: [String: String] = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joinWithSeparator(", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + let userAgent: String = { + if let info = NSBundle.mainBundle().infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let versionString: String + + if #available(OSX 10.10, *) { + let version = NSProcessInfo.processInfo().operatingSystemVersion + versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + } else { + versionString = "10.9" + } + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(OSX) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) + + /// The underlying session. + public let session: NSURLSession + + /// The session delegate handling all the task and session delegate callbacks. + public let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + public var startRequestsImmediately: Bool = true + + /** + The background completion handler closure provided by the UIApplicationDelegate + `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + will automatically call the handler. + + If you need to handle your own events before the handler is called, then you need to override the + SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + + `nil` by default. + */ + public var backgroundCompletionHandler: (() -> Void)? + + // MARK: - Lifecycle + + /** + Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. + + - parameter configuration: The configuration used to construct the managed session. + `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. + - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + default. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance. + */ + public init( + configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /** + Initializes the `Manager` instance with the specified session, delegate and server trust policy. + + - parameter session: The URL session. + - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. + */ + public init?( + session: NSURLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Request + + /** + Creates a request for the specified method, URL string, parameters, parameter encoding and headers. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. + */ + public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + return request(encodedURLRequest) + } + + /** + Creates a request for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. + */ + public func request(URLRequest: URLRequestConvertible) -> Request { + var dataTask: NSURLSessionDataTask! + dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } + + let request = Request(session: session, task: dataTask) + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: - SessionDelegate + + /** + Responsible for handling all delegate callbacks for the underlying session. + */ + public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + private var subdelegates: [Int: Request.TaskDelegate] = [:] + private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + + /// Access the task delegate for the specified task in a thread-safe manner. + public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + get { + var subdelegate: Request.TaskDelegate? + dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } + + return subdelegate + } + set { + dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } + } + } + + /** + Initializes the `SessionDelegate` instance. + + - returns: The new `SessionDelegate` instance. + */ + public override init() { + super.init() + } + + // MARK: - NSURLSessionDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. + public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. + public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. + public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. + public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the session has been invalidated. + + - parameter session: The session object that was invalidated. + - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + */ + public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /** + Requests credentials from the delegate in response to a session-level authentication request from the remote server. + + - parameter session: The session containing the task that requested authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + + /** + Tells the delegate that all messages enqueued for a session have been delivered. + + - parameter session: The session that no longer has any outstanding requests. + */ + public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. + public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. + public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and + /// requires the caller to call the `completionHandler`. + public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. + public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the remote server requested an HTTP redirect. + + - parameter session: The session containing the task whose request resulted in a redirect. + - parameter task: The task whose request resulted in a redirect. + - parameter response: An object containing the server’s response to the original request. + - parameter request: A URL request object filled out with the new location. + - parameter completionHandler: A closure that your handler should call with either the value of the request + parameter, a modified URL request object, or NULL to refuse the redirect and + return the body of the redirect response. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /** + Requests credentials from the delegate in response to an authentication request from the remote server. + + - parameter session: The session containing the task whose request requires authentication. + - parameter task: The task whose request requires authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task] { + delegate.URLSession( + session, + task: task, + didReceiveChallenge: challenge, + completionHandler: completionHandler + ) + } else { + URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) + } + } + + /** + Tells the delegate when a task requires a new request body stream to send to the remote server. + + - parameter session: The session containing the task that needs a new body stream. + - parameter task: The task that needs a new body stream. + - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: NSInputStream? -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /** + Periodically informs the delegate of the progress of sending body content to the server. + + - parameter session: The session containing the data task. + - parameter task: The data task. + - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + - parameter totalBytesSent: The total number of bytes sent so far. + - parameter totalBytesExpectedToSend: The expected length of the body data. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task] as? Request.UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + + /** + Tells the delegate that the task finished transferring data. + + - parameter session: The session containing the task whose request finished transferring data. + - parameter task: The task whose request finished transferring data. + - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + */ + public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidComplete = taskDidComplete { + taskDidComplete(session, task, error) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, didCompleteWithError: error) + } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) + + self[task] = nil + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. + public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. + public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the data task received the initial reply (headers) from the server. + + - parameter session: The session containing the data task that received an initial reply. + - parameter dataTask: The data task that received an initial reply. + - parameter response: A URL response object populated with headers. + - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + constant to indicate whether the transfer should continue as a data task or + should become a download task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: NSURLSessionResponseDisposition -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: NSURLSessionResponseDisposition = .Allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /** + Tells the delegate that the data task was changed to a download task. + + - parameter session: The session containing the task that was replaced by a download task. + - parameter dataTask: The data task that was replaced by a download task. + - parameter downloadTask: The new download task that replaced the data task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) + self[downloadTask] = downloadDelegate + } + } + + /** + Tells the delegate that the data task has received some of the expected data. + + - parameter session: The session containing the data task that provided data. + - parameter dataTask: The data task that provided data. + - parameter data: A data object containing the transferred data. + */ + public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) + } + } + + /** + Asks the delegate whether the data (or upload) task should store the response in the cache. + + - parameter session: The session containing the data (or upload) task. + - parameter dataTask: The data (or upload) task. + - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + caching policy and the values of certain received headers, such as the Pragma + and Cache-Control headers. + - parameter completionHandler: A block that your handler must call, providing either the original proposed + response, a modified version of that response, or NULL to prevent caching the + response. If your delegate implements this method, it must call this completion + handler; otherwise, your app leaks memory. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: NSCachedURLResponse? -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. + public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. + public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that a download task has finished downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that finished. + - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + open the file for reading or move it to a permanent location in your app’s sandbox + container directory before returning from this delegate method. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) + } + } + + /** + Periodically informs the delegate about the download’s progress. + + - parameter session: The session containing the download task. + - parameter downloadTask: The download task. + - parameter bytesWritten: The number of bytes transferred since the last time this delegate + method was called. + - parameter totalBytesWritten: The total number of bytes transferred so far. + - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + header. If this header was not provided, the value is + `NSURLSessionTransferSizeUnknown`. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /** + Tells the delegate that the download task has resumed downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that resumed. See explanation in the discussion. + - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + existing content, then this value is zero. Otherwise, this value is an + integer representing the number of bytes on disk that do not need to be + retrieved again. + - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } + + // MARK: - NSURLSessionStreamDelegate + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + + // MARK: - NSObject + + public override func respondsToSelector(selector: Selector) -> Bool { + #if !os(OSX) + if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + switch selector { + case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return self.dynamicType.instancesRespondToSelector(selector) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 00000000000..5a7ef09c82e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,659 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(OSX) +import CoreServices +#endif + +/** + Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode + multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead + to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the + data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for + larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. + + For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well + and the w3 form documentation. + + - https://www.ietf.org/rfc/rfc2388.txt + - https://www.ietf.org/rfc/rfc2045.txt + - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +*/ +public class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let CRLF = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case Initial, Encapsulated, Final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { + let boundaryText: String + + switch boundaryType { + case .Initial: + boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" + case .Encapsulated: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" + case .Final: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" + } + + return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: [String: String] + let bodyStream: NSInputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: NSError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /** + Creates a multipart form data object. + + - returns: The multipart form data object. + */ + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /** + * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + * information, please refer to the following article: + * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + */ + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String) { + let headers = contentHeaders(name: name) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, mimeType: String) { + let headers = contentHeaders(name: name, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + system associated MIME type. + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String) { + if let + fileName = fileURL.lastPathComponent, + pathExtension = fileURL.pathExtension + { + let mimeType = mimeTypeForPathExtension(pathExtension) + appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) + } else { + let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + } + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + - Content-Type: #{mimeType} (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.fileURL else { + let failureReason = "The file URL does not point to a file URL: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + var isReachable = true + + if #available(OSX 10.10, *) { + isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) + } + + guard isReachable else { + setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + + guard let + path = fileURL.path + where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else + { + let failureReason = "The file URL is a directory, not a file: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + var bodyContentLength: UInt64? + + do { + if let + path = fileURL.path, + fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber + { + bodyContentLength = fileSize.unsignedLongLongValue + } + } catch { + // No-op + } + + guard let length = bodyContentLength else { + let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = NSInputStream(URL: fileURL) else { + let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" + setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) + return + } + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the stream and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + */ + public func appendBodyPart( + stream stream: NSInputStream, + length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part with the headers, stream and length and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - HTTP headers + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter headers: The HTTP headers for the body part. + */ + public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /** + Encodes all the appended body parts into a single `NSData` object. + + It is important to note that this method will load all the appended body parts into memory all at the same + time. This method should only be used when the encoded data will have a small memory footprint. For large data + cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + + - throws: An `NSError` if encoding encounters an error. + + - returns: The encoded `NSData` if encoding is successful. + */ + public func encode() throws -> NSData { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + let encoded = NSMutableData() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encodeBodyPart(bodyPart) + encoded.appendData(encodedData) + } + + return encoded + } + + /** + Writes the appended body parts into the given file URL. + + This process is facilitated by reading and writing with input and output streams, respectively. Thus, + this approach is very memory efficient and should be used for large body part data. + + - parameter fileURL: The file URL to write the multipart form data into. + + - throws: An `NSError` if encoding encounters an error. + */ + public func writeEncodedDataToDisk(fileURL: NSURL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { + let failureReason = "A file already exists at the given file URL: \(fileURL)" + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) + } else if !fileURL.fileURL { + let failureReason = "The URL does not point to a valid file: \(fileURL)" + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) + } + + let outputStream: NSOutputStream + + if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { + outputStream = possibleOutputStream + } else { + let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) + } + + outputStream.open() + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try writeBodyPart(bodyPart, toOutputStream: outputStream) + } + + outputStream.close() + } + + // MARK: - Private - Body Part Encoding + + private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { + let encoded = NSMutableData() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.appendData(initialData) + + let headerData = encodeHeaderDataForBodyPart(bodyPart) + encoded.appendData(headerData) + + let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) + encoded.appendData(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.appendData(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" + } + headerText += EncodingCharacters.CRLF + + return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + + private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { + let inputStream = bodyPart.bodyStream + inputStream.open() + + var error: NSError? + let encoded = NSMutableData() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if inputStream.streamError != nil { + error = inputStream.streamError + break + } + + if bytesRead > 0 { + encoded.appendBytes(buffer, length: bytesRead) + } else if bytesRead < 0 { + let failureReason = "Failed to read from input stream: \(inputStream)" + error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) + break + } else { + break + } + } + + inputStream.close() + + if let error = error { + throw error + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) + try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + } + + private func writeInitialBoundaryDataForBodyPart( + bodyPart: BodyPart, + toOutputStream outputStream: NSOutputStream) + throws + { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try writeData(initialData, toOutputStream: outputStream) + } + + private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let headerData = encodeHeaderDataForBodyPart(bodyPart) + return try writeData(headerData, toOutputStream: outputStream) + } + + private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let inputStream = bodyPart.bodyStream + inputStream.open() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw streamError + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0 { + if outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let streamError = outputStream.streamError { + throw streamError + } + + if bytesWritten < 0 { + let failureReason = "Failed to write to output stream: \(outputStream)" + throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if let + id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), + contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(name name: String) -> [String: String] { + return ["Content-Disposition": "form-data; name=\"\(name)\""] + } + + private func contentHeaders(name name: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"", + "Content-Type": "\(mimeType)" + ] + } + + private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", + "Content-Type": "\(mimeType)" + ] + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(code code: Int, failureReason: String) { + guard bodyPartError == nil else { return } + bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 00000000000..c54e58b32d6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,261 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/** + HTTP method definitions. + + See https://tools.ietf.org/html/rfc7231#section-4.3 +*/ +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} + +// MARK: ParameterEncoding + +/** + Used to specify the way in which a set of parameters are applied to a URL request. + + - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, + and `DELETE` requests, or set as the body for requests with any other HTTP method. The + `Content-Type` HTTP header field of an encoded request with HTTP body is set to + `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification + for how to encode collection types, the convention of appending `[]` to the key for array + values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested + dictionary values (`foo[bar]=baz`). + + - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same + implementation as the `.URL` case, but always applies the encoded result to the URL. + + - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is + set as the body of the request. The `Content-Type` HTTP header field of an encoded request is + set to `application/json`. + + - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, + according to the associated format and write options values, which is set as the body of the + request. The `Content-Type` HTTP header field of an encoded request is set to + `application/x-plist`. + + - `Custom`: Uses the associated closure value to construct a new request given an existing request and + parameters. +*/ +public enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + /** + Creates a URL request by encoding parameters and applying them onto an existing request. + + - parameter URLRequest: The request to have parameters applied. + - parameter parameters: The parameters to apply. + + - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, + if any. + */ + public func encode( + URLRequest: URLRequestConvertible, + parameters: [String: AnyObject]?) + -> (NSMutableURLRequest, NSError?) + { + var mutableURLRequest = URLRequest.URLRequest + + guard let parameters = parameters else { return (mutableURLRequest, nil) } + + var encodingError: NSError? = nil + + switch self { + case .URL, .URLEncodedInURL: + func query(parameters: [String: AnyObject]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sort(<) { + let value = parameters[key]! + components += queryComponents(key, value) + } + + return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") + } + + func encodesParametersInURL(method: Method) -> Bool { + switch self { + case .URLEncodedInURL: + return true + default: + break + } + + switch method { + case .GET, .HEAD, .DELETE: + return true + default: + return false + } + } + + if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { + if let + URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) + where !parameters.isEmpty + { + let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + URLComponents.percentEncodedQuery = percentEncodedQuery + mutableURLRequest.URL = URLComponents.URL + } + } else { + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue( + "application/x-www-form-urlencoded; charset=utf-8", + forHTTPHeaderField: "Content-Type" + ) + } + + mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( + NSUTF8StringEncoding, + allowLossyConversion: false + ) + } + case .JSON: + do { + let options = NSJSONWritingOptions() + let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .PropertyList(let format, let options): + do { + let data = try NSPropertyListSerialization.dataWithPropertyList( + parameters, + format: format, + options: options + ) + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .Custom(let closure): + (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) + } + + return (mutableURLRequest, encodingError) + } + + /** + Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + + - parameter key: The key of the query component. + - parameter value: The value of the query component. + + - returns: The percent-escaped, URL encoded query string components. + */ + public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: AnyObject] { + for (nestedKey, value) in dictionary { + components += queryComponents("\(key)[\(nestedKey)]", value) + } + } else if let array = value as? [AnyObject] { + for value in array { + components += queryComponents("\(key)[]", value) + } + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + + RFC 3986 states that the following characters are "reserved" characters. + + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + - parameter string: The string to be percent-escaped. + + - returns: The percent-escaped string. + */ + public func escape(string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet + allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, OSX 10.10, *) { + escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = index.advancedBy(batchSize, limit: string.endIndex) + let range = startIndex.. Self + { + let credential = NSURLCredential(user: user, password: password, persistence: persistence) + + return authenticate(usingCredential: credential) + } + + /** + Associates a specified credential with the request. + + - parameter credential: The credential. + + - returns: The request. + */ + public func authenticate(usingCredential credential: NSURLCredential) -> Self { + delegate.credential = credential + + return self + } + + /** + Returns a base64 encoded basic authentication credential as an authorization header dictionary. + + - parameter user: The user. + - parameter password: The password. + + - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails. + */ + public static func authorizationHeader(user user: String, password: String) -> [String: String] { + guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } + + let credential = data.base64EncodedStringWithOptions([]) + + return ["Authorization": "Basic \(credential)"] + } + + // MARK: - Progress + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is written to or read + from the server. + + - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected + to write. + - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes + expected to read. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { + if let uploadDelegate = delegate as? UploadTaskDelegate { + uploadDelegate.uploadProgress = closure + } else if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataProgress = closure + } else if let downloadDelegate = delegate as? DownloadTaskDelegate { + downloadDelegate.downloadProgress = closure + } + + return self + } + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + + This closure returns the bytes most recently received from the server, not including data from previous calls. + If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + also important to note that the `response` closure will be called with nil `responseData`. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func stream(closure: (NSData -> Void)? = nil) -> Self { + if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataStream = closure + } + + return self + } + + // MARK: - State + + /** + Resumes the request. + */ + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) + } + + /** + Suspends the request. + */ + public func suspend() { + task.suspend() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) + } + + /** + Cancels the request. + */ + public func cancel() { + if let + downloadDelegate = delegate as? DownloadTaskDelegate, + downloadTask = downloadDelegate.downloadTask + { + downloadTask.cancelByProducingResumeData { data in + downloadDelegate.resumeData = data + } + } else { + task.cancel() + } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) + } + + // MARK: - TaskDelegate + + /** + The task delegate is responsible for handling all delegate callbacks for the underlying task as well as + executing all operations attached to the serial operation queue upon task completion. + */ + public class TaskDelegate: NSObject { + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: NSOperationQueue + + let task: NSURLSessionTask + let progress: NSProgress + + var data: NSData? { return nil } + var error: NSError? + + var initialResponseTime: CFAbsoluteTime? + var credential: NSURLCredential? + + init(task: NSURLSessionTask) { + self.task = task + self.progress = NSProgress(totalUnitCount: 0) + self.queue = { + let operationQueue = NSOperationQueue() + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.suspended = true + + if #available(OSX 10.10, *) { + operationQueue.qualityOfService = NSQualityOfService.Utility + } + + return operationQueue + }() + } + + deinit { + queue.cancelAllOperations() + queue.suspended = false + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: ((NSURLRequest?) -> Void)) + { + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .RejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) + + if credential != nil { + disposition = .UseCredential + } + } + } + + completionHandler(disposition, credential) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + { + var bodyStream: NSInputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + self.error = error + + if let + downloadDelegate = self as? DownloadTaskDelegate, + userInfo = error.userInfo as? [String: AnyObject], + resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData + { + downloadDelegate.resumeData = resumeData + } + } + + queue.suspended = false + } + } + } + + // MARK: - DataTaskDelegate + + class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { + var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } + + private var totalBytesReceived: Int64 = 0 + private var mutableData: NSMutableData + override var data: NSData? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + private var expectedContentLength: Int64? + private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? + private var dataStream: ((data: NSData) -> Void)? + + override init(task: NSURLSessionTask) { + mutableData = NSMutableData() + super.init(task: task) + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: (NSURLSessionResponseDisposition -> Void)) + { + var disposition: NSURLSessionResponseDisposition = .Allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data: data) + } else { + mutableData.appendData(data) + } + + totalBytesReceived += data.length + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + dataProgress?( + bytesReceived: Int64(data.length), + totalBytesReceived: totalBytesReceived, + totalBytesExpectedToReceive: totalBytesExpected + ) + } + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: ((NSCachedURLResponse?) -> Void)) + { + var cachedResponse: NSCachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + + /** + The textual representation used when written to an output stream, which includes the HTTP method and URL, as + well as the response status code if a response has been received. + */ + public var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.HTTPMethod { + components.append(HTTPMethod) + } + + if let URLString = request?.URL?.absoluteString { + components.append(URLString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joinWithSeparator(" ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + func cURLRepresentation() -> String { + var components = ["$ curl -i"] + + guard let + request = self.request, + URL = request.URL, + host = URL.host + else { + return "$ curl command could not be created" + } + + if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { + components.append("-X \(HTTPMethod)") + } + + if let credentialStorage = self.session.configuration.URLCredentialStorage { + let protectionSpace = NSURLProtectionSpace( + host: host, + port: URL.port?.integerValue ?? 0, + protocol: URL.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { + for credential in credentials { + components.append("-u \(credential.user!):\(credential.password!)") + } + } else { + if let credential = delegate.credential { + components.append("-u \(credential.user!):\(credential.password!)") + } + } + } + + if session.configuration.HTTPShouldSetCookies { + if let + cookieStorage = session.configuration.HTTPCookieStorage, + cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } + components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") + } + } + + var headers: [NSObject: AnyObject] = [:] + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders where field != "Cookie" { + headers[field] = value + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value + } + } + + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + + if let + HTTPBodyData = request.HTTPBody, + HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) + { + var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") + escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(URL.absoluteString)\"") + + return components.joinWithSeparator(" \\\n\t") + } + + /// The textual representation used when written to an output stream, in the form of a cURL command. + public var debugDescription: String { + return cURLRepresentation() + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift new file mode 100644 index 00000000000..9c437ff6e41 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,97 @@ +// +// Response.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to store all response data returned from a completed `Request`. +public struct Response { + /// The URL request sent to the server. + public let request: NSURLRequest? + + /// The server's response to the URL request. + public let response: NSHTTPURLResponse? + + /// The data returned by the server. + public let data: NSData? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the `Request`. + public let timeline: Timeline + + /** + Initializes the `Response` instance with the specified URL request, URL response, server data and response + serialization result. + + - parameter request: The URL request sent to the server. + - parameter response: The server's response to the URL request. + - parameter data: The data returned by the server. + - parameter result: The result of response serialization. + - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + + - returns: the new `Response` instance. + */ + public init( + request: NSURLRequest?, + response: NSHTTPURLResponse?, + data: NSData?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - CustomStringConvertible + +extension Response: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } +} + +// MARK: - CustomDebugStringConvertible + +extension Response: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data and the response serialization result. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.length ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joinWithSeparator("\n") + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 00000000000..89e39544b8c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,378 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: ResponseSerializer + +/** + The type in which all response serializers must conform to in order to serialize a response. +*/ +public protocol ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializerType`. + associatedtype SerializedObject + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + associatedtype ErrorObject: ErrorType + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result { get } +} + +// MARK: - + +/** + A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. +*/ +public struct ResponseSerializer: ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializer`. + public typealias SerializedObject = Value + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + public typealias ErrorObject = Error + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result + + /** + Initializes the `ResponseSerializer` instance with the given serialize response closure. + + - parameter serializeResponse: The closure used to serialize the response. + + - returns: The new generic response serializer instance. + */ + public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Default + +extension Request { + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + dispatch_async(queue ?? dispatch_get_main_queue()) { + completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) + } + } + + return self + } + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter responseSerializer: The response serializer responsible for serializing the request, response, + and data. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + responseSerializer: T, + completionHandler: Response -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: timeline + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + + /** + Creates a response serializer that returns the associated data as-is. + + - returns: A data response serializer. + */ + public static func dataResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSData()) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + return .Success(validData) + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func responseData( + queue queue: dispatch_queue_t? = nil, + completionHandler: Response -> Void) + -> Self + { + return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + } +} + +// MARK: - String + +extension Request { + + /** + Creates a response serializer that returns a string initialized from the response data with the specified + string encoding. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + response, falling back to the default HTTP default character set, ISO-8859-1. + + - returns: A string response serializer. + */ + public static func stringResponseSerializer( + encoding encoding: NSStringEncoding? = nil) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success("") } + + guard let validData = data else { + let failureReason = "String could not be serialized. Input data was nil." + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName where convertedEncoding == nil { + convertedEncoding = CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName) + ) + } + + let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding + + if let string = String(data: validData, encoding: actualEncoding) { + return .Success(string) + } else { + let failureReason = "String could not be serialized with encoding: \(actualEncoding)" + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + server response, falling back to the default HTTP default character set, + ISO-8859-1. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseString( + queue queue: dispatch_queue_t? = nil, + encoding: NSStringEncoding? = nil, + completionHandler: Response -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: Request.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + + /** + Creates a response serializer that returns a JSON object constructed from the response data using + `NSJSONSerialization` with the specified reading options. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + + - returns: A JSON object response serializer. + */ + public static func JSONResponseSerializer( + options options: NSJSONReadingOptions = .AllowFragments) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "JSON could not be serialized. Input data was nil or zero length." + let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) + return .Success(JSON) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseJSON( + queue queue: dispatch_queue_t? = nil, + options: NSJSONReadingOptions = .AllowFragments, + completionHandler: Response -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: Request.JSONResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + + /** + Creates a response serializer that returns an object constructed from the response data using + `NSPropertyListSerialization` with the specified reading options. + + - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. + + - returns: A property list object response serializer. + */ + public static func propertyListResponseSerializer( + options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "Property list could not be serialized. Input data was nil or zero length." + let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) + return .Success(plist) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The property list reading options. `0` by default. + - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 + arguments: the URL request, the URL response, the server data and the result + produced while creating the property list. + + - returns: The request. + */ + public func responsePropertyList( + queue queue: dispatch_queue_t? = nil, + options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + completionHandler: Response -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: Request.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift new file mode 100644 index 00000000000..4aabf08bf8b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,103 @@ +// +// Result.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/** + Used to represent whether a request was successful or encountered an error. + + - Success: The request and all post processing operations were successful resulting in the serialization of the + provided associated value. + - Failure: The request encountered an error resulting in a failure. The associated values are the original data + provided by the server as well as the error that caused the failure. +*/ +public enum Result { + case Success(Value) + case Failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .Success: + return true + case .Failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .Success(let value): + return value + case .Failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .Success: + return nil + case .Failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .Success: + return "SUCCESS" + case .Failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .Success(let value): + return "SUCCESS: \(value)" + case .Failure(let error): + return "FAILURE: \(error)" + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 00000000000..7da516e8038 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,304 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +public class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + public let policies: [String: ServerTrustPolicy] + + /** + Initializes the `ServerTrustPolicyManager` instance with the given policies. + + Since different servers and web services can have different leaf certificates, intermediate and even root + certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + pinning for host3 and disabling evaluation for host4. + + - parameter policies: A dictionary of all policies mapped to a particular host. + + - returns: The new `ServerTrustPolicyManager` instance. + */ + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /** + Returns the `ServerTrustPolicy` for the given host if applicable. + + By default, this method will return the policy that perfectly matches the given host. Subclasses could override + this method and implement more complex mapping implementations such as wildcards. + + - parameter host: The host to use when searching for a matching policy. + + - returns: The server trust policy for the given host if found. + */ + public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension NSURLSession { + private struct AssociatedKeys { + static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/** + The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when + connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust + with a given set of criteria to determine whether the server trust is valid and the connection should be made. + + Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other + vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged + to route all communication over an HTTPS connection with pinning enabled. + + - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to + validate the host provided by the challenge. Applications are encouraged to always + validate the host in production environments to guarantee the validity of the server's + certificate chain. + + - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is + considered valid if one of the pinned certificates match one of the server certificates. + By validating both the certificate chain and host, certificate pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered + valid if one of the pinned public keys match one of the server certificate public keys. + By validating both the certificate chain and host, public key pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. + + - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. +*/ +public enum ServerTrustPolicy { + case PerformDefaultEvaluation(validateHost: Bool) + case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case DisableEvaluation + case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) + + // MARK: - Bundle Location + + /** + Returns all certificates within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `.cer` files. + + - returns: All certificates within the given bundle. + */ + public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) + }.flatten()) + + for path in paths { + if let + certificateData = NSData(contentsOfFile: path), + certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /** + Returns all public keys within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `*.cer` files. + + - returns: All public keys within the given bundle. + */ + public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificatesInBundle(bundle) { + if let publicKey = publicKeyForCertificate(certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /** + Evaluates whether the server trust is valid for the given host. + + - parameter serverTrust: The server trust to evaluate. + - parameter host: The host of the challenge protection space. + + - returns: Whether the server trust is valid. + */ + public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .PerformDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateDataForTrust(serverTrust) + let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData.isEqualToData(pinnedCertificateData) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .DisableEvaluation: + serverTrustIsValid = true + case let .CustomEvaluation(closure): + serverTrustIsValid = closure(serverTrust: serverTrust, host: host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType(kSecTrustResultInvalid) + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType(kSecTrustResultUnspecified) + let proceed = SecTrustResultType(kSecTrustResultProceed) + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateDataForTrust(trust: SecTrust) -> [NSData] { + var certificates: [SecCertificate] = [] + + for index in 0.. [NSData] { + return certificates.map { SecCertificateCopyData($0) as NSData } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust where trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift new file mode 100644 index 00000000000..e463d9b2f81 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -0,0 +1,182 @@ +// +// Stream.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if !os(watchOS) + +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) +extension Manager { + private enum Streamable { + case Stream(String, Int) + case NetService(NSNetService) + } + + private func stream(streamable: Streamable) -> Request { + var streamTask: NSURLSessionStreamTask! + + switch streamable { + case .Stream(let hostName, let port): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithHostName(hostName, port: port) + } + case .NetService(let netService): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithNetService(netService) + } + } + + let request = Request(session: session, task: streamTask) + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + /** + Creates a request for bidirectional streaming with the given hostname and port. + + - parameter hostName: The hostname of the server to connect to. + - parameter port: The port of the server to connect to. + + - returns: The created stream request. + */ + public func stream(hostName hostName: String, port: Int) -> Request { + return stream(.Stream(hostName, port)) + } + + /** + Creates a request for bidirectional streaming with the given `NSNetService`. + + - parameter netService: The net service used to identify the endpoint. + + - returns: The created stream request. + */ + public func stream(netService netService: NSNetService) -> Request { + return stream(.NetService(netService)) + } +} + +// MARK: - + +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) +extension Manager.SessionDelegate: NSURLSessionStreamDelegate { + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. + public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. + public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. + public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. + public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + // MARK: Delegate Methods + + /** + Tells the delegate that the read side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /** + Tells the delegate that the write side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /** + Tells the delegate that the system has determined that a better route to the host is available. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /** + Tells the delegate that the stream task has been completed and provides the unopened stream objects. + + - parameter session: The session. + - parameter streamTask: The stream task. + - parameter inputStream: The new input stream. + - parameter outputStream: The new output stream. + */ + public func URLSession( + session: NSURLSession, + streamTask: NSURLSessionStreamTask, + didBecomeInputStream inputStream: NSInputStream, + outputStream: NSOutputStream) + { + streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift new file mode 100644 index 00000000000..21971e6e465 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -0,0 +1,376 @@ +// +// Upload.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Manager { + private enum Uploadable { + case Data(NSURLRequest, NSData) + case File(NSURLRequest, NSURL) + case Stream(NSURLRequest, NSInputStream) + } + + private func upload(uploadable: Uploadable) -> Request { + var uploadTask: NSURLSessionUploadTask! + var HTTPBodyStream: NSInputStream? + + switch uploadable { + case .Data(let request, let data): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) + } + case .File(let request, let fileURL): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) + } + case .Stream(let request, let stream): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithStreamedRequest(request) + } + + HTTPBodyStream = stream + } + + let request = Request(session: session, task: uploadTask) + + if HTTPBodyStream != nil { + request.delegate.taskNeedNewBodyStream = { _, _ in + return HTTPBodyStream + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: File + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return upload(.File(URLRequest.URLRequest, file)) + } + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + return upload(mutableURLRequest, file: file) + } + + // MARK: Data + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return upload(.Data(URLRequest.URLRequest, data)) + } + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, data: data) + } + + // MARK: Stream + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return upload(.Stream(URLRequest.URLRequest, stream)) + } + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, stream: stream) + } + + // MARK: MultipartFormData + + /// Default memory threshold used when encoding `MultipartFormData`. + public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 + + /** + Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + associated values. + + - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with + streaming information. + - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + error. + */ + public enum MultipartFormDataEncodingResult { + case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) + case Failure(ErrorType) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload( + mutableURLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + let formData = MultipartFormData() + multipartFormData(formData) + + let URLRequestWithContentType = URLRequest.URLRequest + URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + do { + let data = try formData.encode() + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, data: data), + streamingFromDisk: false, + streamFileURL: nil + ) + + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } else { + let fileManager = NSFileManager.defaultManager() + let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") + let fileName = NSUUID().UUIDString + let fileURL = directoryURL.URLByAppendingPathComponent(fileName) + + do { + try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) + try formData.writeEncodedDataToDisk(fileURL) + + dispatch_async(dispatch_get_main_queue()) { + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, file: fileURL), + streamingFromDisk: true, + streamFileURL: fileURL + ) + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } + } + } +} + +// MARK: - + +extension Request { + + // MARK: - UploadTaskDelegate + + class UploadTaskDelegate: DataTaskDelegate { + var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } + var uploadProgress: ((Int64, Int64, Int64) -> Void)! + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + progress.totalUnitCount = totalBytesExpectedToSend + progress.completedUnitCount = totalBytesSent + + uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 00000000000..b94e07d1e4e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,214 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + + /** + Used to represent whether validation was successful or encountered an error resulting in a failure. + + - Success: The validation was successful. + - Failure: The validation failed encountering the provided error. + */ + public enum ValidationResult { + case Success + case Failure(NSError) + } + + /** + A closure used to validate a request that takes a URL request and URL response, and returns whether the + request was valid. + */ + public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult + + /** + Validates the request, using the specified closure. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter validation: A closure to validate the request. + + - returns: The request. + */ + public func validate(validation: Validation) -> Self { + delegate.queue.addOperationWithBlock { + if let + response = self.response where self.delegate.error == nil, + case let .Failure(error) = validation(self.request, response) + { + self.delegate.error = error + } + } + + return self + } + + // MARK: - Status Code + + /** + Validates that the response has a status code in the specified range. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter range: The range of acceptable status codes. + + - returns: The request. + */ + public func validate(statusCode acceptableStatusCode: S) -> Self { + return validate { _, response in + if acceptableStatusCode.contains(response.statusCode) { + return .Success + } else { + let failureReason = "Response status code was unacceptable: \(response.statusCode)" + + let error = NSError( + domain: Error.Domain, + code: Error.Code.StatusCodeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.StatusCode: response.statusCode + ] + ) + + return .Failure(error) + } + } + } + + // MARK: - Content-Type + + private struct MIMEType { + let type: String + let subtype: String + + init?(_ string: String) { + let components: [String] = { + let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) + let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) + return split.componentsSeparatedByString("/") + }() + + if let + type = components.first, + subtype = components.last + { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(MIME: MIMEType) -> Bool { + switch (type, subtype) { + case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + /** + Validates that the response has a content type in the specified array. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + + - returns: The request. + */ + public func validate(contentType acceptableContentTypes: S) -> Self { + return validate { _, response in + guard let validData = self.delegate.data where validData.length > 0 else { return .Success } + + if let + responseContentType = response.MIMEType, + responseMIMEType = MIMEType(responseContentType) + { + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { + return .Success + } + } + } else { + for contentType in acceptableContentTypes { + if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { + return .Success + } + } + } + + let contentType: String + let failureReason: String + + if let responseContentType = response.MIMEType { + contentType = responseContentType + + failureReason = ( + "Response content type \"\(responseContentType)\" does not match any acceptable " + + "content types: \(acceptableContentTypes)" + ) + } else { + contentType = "" + failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" + } + + let error = NSError( + domain: Error.Domain, + code: Error.Code.ContentTypeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.ContentType: contentType + ] + ) + + return .Failure(error) + } + } + + // MARK: - Automatic + + /** + Validates that the response has a status code in the default acceptable range of 200...299, and that the content + type matches any specified in the Accept HTTP header field. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - returns: The request. + */ + public func validate() -> Self { + let acceptableStatusCodes: Range = 200..<300 + let acceptableContentTypes: [String] = { + if let accept = request?.valueForHTTPHeaderField("Accept") { + return accept.componentsSeparatedByString(",") + } + + return ["*/*"] + }() + + return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json new file mode 100644 index 00000000000..42589f905bb --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -0,0 +1,25 @@ +{ + "name": "PetstoreClient", + "platforms": { + "ios": "8.0", + "osx": "10.9" + }, + "version": "0.0.1", + "source": { + "git": "git@github.com:swagger-api/swagger-mustache.git", + "tag": "v1.0.0" + }, + "authors": "", + "license": "Apache License, Version 2.0", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", + "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", + "dependencies": { + "RxSwift": [ + "~> 2.0" + ], + "Alamofire": [ + "~> 3.4.1" + ] + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 00000000000..20a1e6250c4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,22 @@ +PODS: + - Alamofire (3.4.2) + - PetstoreClient (0.0.1): + - Alamofire (~> 3.4.1) + - RxSwift (~> 2.0) + - RxSwift (2.6.0) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: "../" + +SPEC CHECKSUMS: + Alamofire: 6aa33201d20d069e1598891cf928883ff1888c7a + PetstoreClient: 1090d122e1fe799cb172d74af3445a6945370a59 + RxSwift: 77f3a0b15324baa7a1c9bfa9f199648a82424e26 + +PODFILE CHECKSUM: cedb3058b02f4776d7c31f6d92ae2f674fdf424d + +COCOAPODS: 1.0.0 diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..c44bf686236 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1743 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 00A528BBED5B1D5DF26B8ADE64C5B3F2 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69E4AF865DEA1313D953D5D999EB66D9 /* CompositeDisposable.swift */; }; + 00D1D0E4C3E6F9EA952C2EDEF2C13DE9 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 893CB8DCF25ADBB99031B207B1A6C6D7 /* NopDisposable.swift */; }; + 0268E70939A7BFBC91C0557D16DDD027 /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 307A5528A2C4C2361F08E104A787F806 /* ScheduledDisposable.swift */; }; + 028C4C90CAA75222DAA6CA7B37F16A84 /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = F17674406359B17ECA62D6F4F62CE140 /* ConcurrentDispatchQueueScheduler.swift */; }; + 030667BEF4154402A2317126A893E459 /* ConnectableObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00BA2EEB61EC81F2780197C863C8E05B /* ConnectableObservable.swift */; }; + 04509FBE687E186C45C9E2F78E6F6946 /* CombineLatest+CollectionType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C75D367A5167A68A60279B4218AC83C6 /* CombineLatest+CollectionType.swift */; }; + 0487B12B08D927162A20CB2A56A2D077 /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB4CC27373795992C949EB261869D25D /* Just.swift */; }; + 04923B3851BD1F857A9B207EE9EC8CDB /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6674B43168347A74679915BC8E23CEEB /* SubjectType.swift */; }; + 0607BCCDD781FF7FFD3629BF4A8BAD23 /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 107044D71C2AC150AAF28FD7DBC5BE35 /* Sample.swift */; }; + 07E83400AACF1430C5B3DF482167A0F1 /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 871187CA85FEE565F015ABAE28232F63 /* Reduce.swift */; }; + 08D2C4B252A264F837733A22CBFB2481 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CB6241FE221077DEEAFBF12B7662DE3 /* Error.swift */; }; + 0A5F6F590DCE147853B2E21487ABA4AA /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5663B56546A40CF4D9DC4E08F05CF9A /* RetryWhen.swift */; }; + 0A9698AC9DD60FC3721809C6AB9BCE81 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; + 0AEB6185484DD9137068A40CE70D4B85 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBF34B9E74264B0313658E8FC445AF7C /* SchedulerServices+Emulation.swift */; }; + 0D6AD3708152BB59E38D5839A0B0377F /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E29B122E21967769A1A67483CF0E9B3 /* Map.swift */; }; + 107E73472222CFD28A8C640F332DA52A /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 174587C7E166EDD81F62A533BF855010 /* Scan.swift */; }; + 110E6B43666A729745E9980F080944C4 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */; }; + 12999CCB3E22F57CB230F85534EF6930 /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B8CDA72BC4EB0297E6B427528093D09 /* SingleAssignmentDisposable.swift */; }; + 14DD51004DF8C27A7D0491AEFEC5F464 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + 159C262BD23A08981D11D3B94340848B /* SynchronizedSubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C02D69889BAB0CD549F6E8B7AB1E906 /* SynchronizedSubscribeType.swift */; }; + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 236369DA7426FBB45E8EDCC452D29C35 /* Timeline.swift */; }; + 165531B0C3FF4D343825C3DB0B79FD68 /* Observable+Time.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69756B9C78B48FF74CD369EFCDE9C2B1 /* Observable+Time.swift */; }; + 1A11209BABC1DE84187BFAEA3E91602D /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A1DFDC8C172C170471AD51E8387245D /* RxMutableBox.swift */; }; + 1CBCB4FF2C9CDB144871C2A0856EB44D /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 124CDC65B696C8DC861A12328CC0F15E /* ConnectableObservableType.swift */; }; + 2023E24B94C04CC05DDFB499ECA760FB /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = E884CFDBB07F3CB079CE908979ECB598 /* Never.swift */; }; + 207AB9AAE48F202AF774554ED7545D98 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A076FA46214932ED98BF355FD36239A /* InvocableScheduledItem.swift */; }; + 22C91CF507223CEE1A7E1302E912DC8B /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CD5B3237A6E093FFA4F2997C134F2DD /* AddRef.swift */; }; + 22C9E40BB4DFB30DAAFD8555EF69BC08 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1D3C1000B643672DC644FD0CBE24A8 /* HistoricalScheduler.swift */; }; + 23CA1BD96C4742DE71082211C8DBFF5F /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C3336183F2A5A748C53087E6C5CCB26 /* SchedulerType.swift */; }; + 252E1D07E589566E0B8F49C2B9131976 /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEE22BA1BE31E7D0A0B5BF1B464EF7CC /* WithLatestFrom.swift */; }; + 26E95A382D3F6848E571EF506D91B1C1 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E20497D5F106B70BA10AFEB21CA855FA /* InvocableType.swift */; }; + 2BEA24EE395DA16EFEBC08B8D450F00A /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BDB15E6DB9E373B0AD0499AFC07284 /* ObservableType.swift */; }; + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEB263E7AF9CDED7D6E05CE40D939240 /* Validation.swift */; }; + 2DF21CC164C25ED6947C67198879DE12 /* Variable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D13D4B9C215DA186C0A3E5B1932B3D29 /* Variable.swift */; }; + 313FCC5057970674AB6016DEF7A05902 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28A18D960F2A71740B74380466850EFA /* SynchronizedUnsubscribeType.swift */; }; + 3200EF8FA76EE92E0108DF928FB39CCB /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26E73BA869E104BC817E6A4EE0F6BFFE /* Switch.swift */; }; + 33393FE8FB3933A22617E02FA3FFA780 /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 032DA67F177D4161CBEB8BD61FA17071 /* Skip.swift */; }; + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96A79AA09F5647BD1FF7A9E49D5DA5C3 /* NetworkReachabilityManager.swift */; }; + 393372CC0F931D0D192179C4B16DF65E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + 39F4B474510DFC1711DD2EF809EA101B /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = D47AC1CB336615BAAC40EEC13860795D /* Catch.swift */; }; + 3AAB4B14DB0A02456F909B482400C142 /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FD520A0B67F84361BFA33C7418244A3 /* DistinctUntilChanged.swift */; }; + 3ADB6687421BF63BCC8A8C8D62E0C4F2 /* RefCount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6225D2C450CDCF3D7A748BA49E45B97D /* RefCount.swift */; }; + 3DAFF4DA4C977B85B5C5B35728001AF2 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8E8FBD5D0739C97C372A6073AC616EE /* Concat.swift */; }; + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D29DC2DC35087E0FB07AE49D5D693C1 /* ResponseSerialization.swift */; }; + 3EE9F1D7EB9C05CB5821E18136EF812E /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FA4C042B453E02311BC876D6F21BDE7 /* SingleAsync.swift */; }; + 402BB7DBAC4D93AD381A0075D7BDDDBA /* Zip+CollectionType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0038480FC536F454DACB4DBE1E10094B /* Zip+CollectionType.swift */; }; + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F9414D2D4412FCB719C37DB1F9A122B /* Manager.swift */; }; + 4266AE0D8F9A4FA69F408AAC9118320A /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAD7CCDEF0C0B768218C2662276F4902 /* Merge.swift */; }; + 434C2C5108A8B9EEA916566F7DB0EDF6 /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EB91AB4E00273BC81BDB9A8724669F2 /* Deferred.swift */; }; + 437C3354F611D5412125ADF24F4FDEE1 /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4394A584E7D89F9FB5B789CB755067DC /* Rx.swift */; }; + 480B2F9937EF953E12DE12FCB177C32A /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48CCF08CD6920361C24CF3A22A56A7AC /* TakeLast.swift */; }; + 498A556404BCE59DD962113CD29165A0 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7766171C5E635B853B5374F01544B689 /* Errors.swift */; }; + 4A216C127342712EDE589085CBB58962 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE40AF57E15052EF477B40E33879F683 /* ElementAt.swift */; }; + 4AE52A909A95E3E4A6DC2F48BD8FC758 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 013B18D5D7BF1208DB3103CFB973DCD6 /* SerialDisposable.swift */; }; + 4B059D5D108F9D2A4E51A6D1B477A2F5 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; + 4C5244B7F2D69F1DFC083E31070E3B0F /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 833063D9EDB0A6FDC729B019C944CC81 /* Sink.swift */; }; + 4CA85A5CF8897D7D46BC6D0D76C8189A /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04278C1CC34204EF9733A22C2EA2FD0F /* Producer.swift */; }; + 4DB1B23F5FAF7C5E02520AFE08646AF2 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5ACFE2C40780B40C48574E06FA048AE /* BinaryDisposable.swift */; }; + 4E1394BCD39E2E3470805196E884B68B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 4EF8849290BCC9D36D8D75969F6753E7 /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3882A5E8DEB676D211220F11769089C3 /* ScheduledItem.swift */; }; + 4F8D754FA3405C5B692B644166A0F02A /* AnonymousObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E449EE7665AC03F6CB4C69C078A2C6E1 /* AnonymousObservable.swift */; }; + 501A111A5AE07BC13E3265DB49EE0A1B /* Observable+Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A5B195ED13C7B5812C1C19D9A0AF4E7 /* Observable+Debug.swift */; }; + 527C7425A5831BFC30CC9EC216506393 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85785AC2F7131137CEC1AA518A99821 /* TailRecursiveSink.swift */; }; + 54325B7F87498350C604C429751BEC97 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; + 55D355CC26824B52E1A7420802FB5DC5 /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F3BD79A2222142FAFB325DA25C25B93 /* ImmediateSchedulerType.swift */; }; + 569684CF06CEDCEA569BEC7910FC6E5B /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; + 58023FA401993154E36E604471265263 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54FB4EAB8FE7EB1FAAF54C2CD669407F /* DisposeBase.swift */; }; + 58344FE826FA6ED012A3450ACB0BF93D /* RxSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */; }; + 5997C0F97BD6687648224D5C6442B862 /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC62C1534DF3C33EADA5A490B5AE9CDA /* DelaySubscription.swift */; }; + 5B721FAF55FEDB8046F23843565833A2 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5992242BCBCCD7195DCB2E5DD5AAF03F /* Repeat.swift */; }; + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3AF641ABBC688B16196427A4F87AC9 /* Upload.swift */; }; + 5BD263D28F10A84969A6521CA166957C /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95805B1F937B0B277A4436B1CC9D36A8 /* Empty.swift */; }; + 5BDF0811AEFBD49A7DE4AF35DA3BD34F /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26DC12270A3810F7571A22ADA1B2E3C3 /* Multicast.swift */; }; + 5C8C1A80AB947F293430868D52A910C2 /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72E00C987CFA33BA8118B62116109E5C /* HistoricalSchedulerTimeConverter.swift */; }; + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E8FB7417C3CF49AE4BB883A3D0B1701 /* Download.swift */; }; + 5CF87E88489D3832C46FAFCE191F78F9 /* TakeWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF11B71848EE4F7F9EB65BD8619E9F34 /* TakeWhile.swift */; }; + 6007585CC5912D979404BDB047CD36C4 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = C92F3601F527E23AF6A2887AABB8A93F /* Platform.Darwin.swift */; }; + 618251D2C3027F214154D2CDFE1900AB /* Observable+Creation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577931910F552C8D583E4F06297AE5F0 /* Observable+Creation.swift */; }; + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CF9A02E2D7DB5CB8F88A2B416E845CE /* Response.swift */; }; + 6414AAC9ED1AD7417B005D50D04341F5 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A372EE18837587E94712F2D33A5A25F /* ObserveOn.swift */; }; + 66D9046FEDE40E6732F8B3E090007268 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A81E73C3EA60E53695BDA2B8A16A92 /* RefCountDisposable.swift */; }; + 68614EDB167FFFA6FBEC851368044FB3 /* Observable+Multiple.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB8353298303C7BF494403F3677F02B7 /* Observable+Multiple.swift */; }; + 69AC467220269CE474E1C1156912C9DD /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 417B31FE938008356C6948F57BCE692B /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 717576C9ABD8ABE8163D441ABE1C4A8D /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4F3C53CFE3E02A3D827152998ED3269 /* SynchronizedOnType.swift */; }; + 725EED04ED27CA8159CB2683F1EFD45A /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 72CF8071AF37B85C1DE763805C39A3AB /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = B075E56C75F06E89FF786E9497A7BF1D /* Lock.swift */; }; + 731E6ACE4939DCE8F6AF47FA1A00D595 /* Observable+Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CBDF4BE3A5447A1A092129A27CB712 /* Observable+Single.swift */; }; + 751E794A58F9FCB7738D4ED30D10DD19 /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A29FE9D0351954C77F9749A80112D24 /* AnyObserver.swift */; }; + 7574EBA19BA114D77C76D2CC1B58E73C /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62716568919652C42C9CE8CE08BA1BC1 /* Timeout.swift */; }; + 75D86B4420906282E6B3393E98837360 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; + 77D1DB57FAA744C6ECBA7242836D6479 /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A04C65CAE7ECACBA7F91B893BF515EC3 /* AnonymousObserver.swift */; }; + 79F6454BBF28D094A211494E22A07327 /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = B59F044C2F3AA0F88DA1E524A6E19DAD /* SkipUntil.swift */; }; + 7A6597623E723E6F8350D2CA30A2CD9C /* Observable+Aggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D7D5684003E0341A47DFDC1F5ADEDE4 /* Observable+Aggregate.swift */; }; + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE4B2A92C93C96C8B19538C86BF4C9B3 /* ServerTrustPolicy.swift */; }; + 7E11CAC09AC72BD412078441E2F7BC21 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CEE4BCEFD46808967A306CE2FE52BE7 /* VirtualTimeConverterType.swift */; }; + 7E6DD4CEE210B03B7E3A0F01A36A7624 /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 039008973BB72A292E730497A11A8863 /* Sequence.swift */; }; + 7F8297BE677C9A67B915F044DB16C0BE /* ShareReplay1WhileConnected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 349A4282992FE83BD930BDE9553299B9 /* ShareReplay1WhileConnected.swift */; }; + 7F82F4EE1BA91C32CE75312176ACD4F0 /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6564B4424B5F7C755C24BD43C38EC5E5 /* Take.swift */; }; + 82DB09296E2BC713C6D363528657A3FD /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50D58CB31D4E74CF5CC37D60F68B493A /* ToArray.swift */; }; + 84B43422CBE09278E477D1BFF27B07A1 /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B2DD91E9F30A7E4967B6A344D389C44 /* Window.swift */; }; + 84B93CFEFA6412E49988C92153998357 /* AnonymousInvocable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1ED40A755F10A4696EA0CBB2D7FEE85 /* AnonymousInvocable.swift */; }; + 85E0465919F9DC7C97DD593CB49BB5E0 /* ShareReplay1.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5CDD03686D25AF1BF04A28DBB0D83D2 /* ShareReplay1.swift */; }; + 8634F37209E5506667C604C1973F630D /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; + 88CCC2ADA43F75CB4708A701F5031643 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91023257BB0F8F89168BED72C9D18A04 /* ObserverBase.swift */; }; + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8B68A752ED9CC80E5478E4FEC5A5F721 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; + 8BDC4F0F424CA9A8190F28E7A02417A8 /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B67FE3B78F251062560D5B54332F8488 /* Cancelable.swift */; }; + 8D3CD54E3BACC9DB116DDA2DC30420CF /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 209AA17DAFB4137150A4B269C8D61D46 /* ObserverType.swift */; }; + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08411B5538F3A7C67CFF13F4C5EF3B2A /* Alamofire.swift */; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + 92450B928E8001F2B28A80072611F4C1 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 491C7768EB60DF34EA12C24849C2D72F /* Error.swift */; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C50A6F0BDAFC21594FAFC3C626AFD1D2 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9543E1505CCD2189D86456DAA0D55A22 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD198F0512985543E25A9FBDD7D6BC7 /* BehaviorSubject.swift */; }; + 956216483BCB853794F52B0292831E9C /* DispatchQueueSchedulerQOS.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBCA5397A4618572E794E81BBBAF486B /* DispatchQueueSchedulerQOS.swift */; }; + 96A03A2C4325A59DE2B02913FE351815 /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6EAA1E1ACF9BD144EB4E8FF2EB56C8C /* BooleanDisposable.swift */; }; + 97AB8959ABA0C9B8D4F400FD814BBB65 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; + 983C8A7CA7087B8FD905B6392B05B790 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; + 98FA1CFF63A5E74A7DB3255DA60C1843 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58D0E9FFEEC555EF3D53C7FEB94A90AF /* DisposeBag.swift */; }; + 99F6DFF51E7C238DF99CA788144C732A /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = D96789E22AD200745F369A8171A18AE9 /* CombineLatest.swift */; }; + 9C3C83B09DE882AA526C40FDA31B69C8 /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12C5111A9F88E244A38CA56C1276C125 /* Throttle.swift */; }; + 9C824A364077ED1458CEF9776F2FB44A /* String+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEDBB4F4415D38EEFF0B0532A8AB6D2E /* String+Rx.swift */; }; + 9FDB94097AD437CDE44A507037AE4010 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + A0A18CB5F889D7C2F80D6024EA568BEA /* Observable+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74EC64ED13811CA9471CD3CE2ECE0B62 /* Observable+Concurrency.swift */; }; + A1B963DD34D20B255430C99DD78A1D43 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; + A23E9C4262ED3ED9FF20A9E6E1FA2121 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7710661431185B0AF05251F7C5C5B6B3 /* SerialDispatchQueueScheduler.swift */; }; + A4FBC2BD1A93FA52B5C97E79CDB9302F /* ImmediateScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9B8E0AD4CAA3B322ABD3B211D352E49 /* ImmediateScheduler.swift */; }; + A606E44DA4B92B1FFBA177125D55F6AA /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BCFEBA50D572B696909D7D41BAB79AB /* Buffer.swift */; }; + A67CCBFC004EF58E785FA7ED4A1B69B6 /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41CE3CC9A5CC39149C281EE98E90DD06 /* Generate.swift */; }; + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44F2ACF7E9C031E03B07A7BBAC875B7F /* Result.swift */; }; + AC265ECE8E2AF91D58A755022E7DF802 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CAD5539CBA152B38C00AA245AB29284 /* PriorityQueue.swift */; }; + AD9D268210ED449C3BE591513FD0CFB8 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F447156B743BC57A765F3E625485703 /* RecursiveScheduler.swift */; }; + ADC582F488BC636CC4292513053F6992 /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 801E5BB24BC33733C0DB65AD5D8184D3 /* AsyncLock.swift */; }; + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1CB77666BCB3637056A25CE3EBA0F469 /* Alamofire-dummy.m */; }; + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = B50291BA734D2D01C64FD306DE8755C9 /* Stream.swift */; }; + AF3E5D2CE5E3448DB881E0F40F2F334F /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6786D5EBEC19CE47B39AAA29EF60C40D /* Do.swift */; }; + AFF9AA31B242BF7F011D018D1B2A12FC /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; + B0EAF63B91ABFD39C96353392D157D19 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47A47359019C20FADB3204C4ACD9E332 /* Zip.swift */; }; + B0F20FEA2B9A800D016EF5B46EFDECE9 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71BBD80B0287AD0696ECFB9E594CC1A1 /* CombineLatest+arity.swift */; }; + B22405A127912A4943AEFBDD57E7A267 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DE7502D330E44C08B1F7A81D8F56963 /* AnonymousDisposable.swift */; }; + B28CA824CA5CD903042D8A07E9C5950E /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E3482AC7A6F3044A3B7F9F260FACCE4 /* ReplaySubject.swift */; }; + B33369A55E29C11FA5F5977B5A47F1D4 /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4CF09B7E555E5751AA869EE6A419F9E8 /* RxSwift-dummy.m */; }; + B45CADB404E006E0EA39D7239C81C64F /* StableCompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99127A798646251A08D12F15E0848F88 /* StableCompositeDisposable.swift */; }; + B590B3C59D3A327452D2532766F2F630 /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2607E6E8AFF3EECBB571B72B0D1F59CF /* MainScheduler.swift */; }; + B754E33E17893DF35DECA754DE819A66 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B90561BFCE4E31D197F5EEDD205617F /* Queue.swift */; }; + B7DCF4199B0EEF4CB2FE0DFF23F99049 /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = B01AD6F6AA11897970B6FF1F85239450 /* SkipWhile.swift */; }; + BB03FC085AE6A19821878DE92116DDD5 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; + BB3A568E8ED6C1792B43708A36A66F3D /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA3CFBEC085617E86B78D9C8DCA19F82 /* Event.swift */; }; + BB5C8DC43B5072BBC05F56BF4DFD8CC5 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9B46E628DE07A2596AD75B742E148BC /* Zip+arity.swift */; }; + BC10CEE813861D2F71E501E2F06532AB /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70C9C312AA84856756C184379F21100D /* ScheduledItemType.swift */; }; + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04443F5A669B9694BEF5EB3BE6BAAE07 /* Notifications.swift */; }; + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = C00667BAC6E66709B455A4791117BB57 /* ParameterEncoding.swift */; }; + C3739BDF471B57AECC84085608EC9CE6 /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = A728EA00016FD91834126F5AEA1E3A9D /* InfiniteSequence.swift */; }; + C5099A3F4D955165F503506F2D10065D /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C9E156C15F63A992E8CB37F9A50E6D1 /* SynchronizedDisposeType.swift */; }; + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; + C6EFFFF6D9947B99945FE08559733EF6 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10CB3D5DB99AC32CF878965519F3B41B /* Timer.swift */; }; + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14ACCC553ABB39FB00F047DA250ED44C /* MultipartFormData.swift */; }; + CA4A98FD2226B57E5F59E0BA2E1A97EC /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE12CC67B55FF5D86267EFF452D23F58 /* OperationQueueScheduler.swift */; }; + CD00FDDA48E9BC390530672F9F09D8CF /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF45CBC0BB14D377AE86709A7C9BB7E0 /* Amb.swift */; }; + CDF08B0C84BE839E79DF99C271453406 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 315C6F02302A95859FB437750811D16C /* SubscriptionDisposable.swift */; }; + CF13D1D873436D3890EC7392DEDE0B3E /* ObserveOnSerialDispatchQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7318F7B1BEFE5935B6F3D1208C7A07D /* ObserveOnSerialDispatchQueue.swift */; }; + D0F5068C6F5C0489E8A41A9912A09016 /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1B8553865AA7FC5E48F0EFCC43EF1E5 /* Range.swift */; }; + D180CF545583D5DCDF770FBAA36F5DB0 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA4EB37CDC7CB7862DFA4AB2A4F30266 /* Filter.swift */; }; + D190592C39D806474770AF30FCC4EF4E /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24716D0E21B0DC160D43515DCC16DABE /* Bag.swift */; }; + D4789D8318C97E380412D03C1C321A88 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CB5D30407CA9653D9CCF2F93C2B5CB9 /* Platform.Linux.swift */; }; + D5ECB1C860D3F53280EE2C5E54D470BD /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8910C8F9A813CED4DAA22900102E6B35 /* Using.swift */; }; + D932A3F3727B26175B547BA865A76B81 /* TakeUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 185BAC8C4C600A1E781B848207964435 /* TakeUntil.swift */; }; + D99C59116FC2BC799C9C9DE4D0282EB9 /* Observable+Binding.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE5C8F881BB25EDFF298416A85915112 /* Observable+Binding.swift */; }; + DA18B15A9632B7282CF91FE4771C0B60 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54CD9FADE39EF69EAD6845394C0B31B4 /* Observable.swift */; }; + DA202CAFA730E897B4D302C8C603A7E1 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; + DB5B0A5C01527330DCD4CEF9740C7140 /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3E50C8032DD5CE4271A38EA13EC1B7E /* PublishSubject.swift */; }; + DC9EF51CEA903F88D43F7B3A96923DFD /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0A02687B1778ABBE05DC52DD87D428 /* SubscribeOn.swift */; }; + DFF7D509E6FC70067A71C1CF0441AD48 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E16A421C7269D0E81CB5E59344E63391 /* NAryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8786CF728CE1174F80409B6D56DEF6BD /* NAryDisposable.swift */; }; + E315A5FF56451DF73C7FE3140D5E2C6C /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A677E2624A679FA6A7B5E795BB5B04 /* ObservableConvertibleType.swift */; }; + E51F4BE281ADBC629708A4D131E9190C /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60057AA4C3D045344B41F9CBFBE2F8D3 /* Disposable.swift */; }; + E61B26D220A1A27E3BE7AD3F9BE35C76 /* Observable+StandardSequenceOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79FB4FB8DD0A8BFD4AEDF7FC691EA462 /* Observable+StandardSequenceOperators.swift */; }; + E8CAB3FA190277C8E609F992A51EA9D2 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21174758D397BBC916241AFE05CDC8A8 /* StartWith.swift */; }; + ECFCC7B806126EF7788D0DE094711905 /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68C7B45B8F12061A28461A80B8BCF3CD /* CurrentThreadScheduler.swift */; }; + EE42701AD3887754AF7695978852957E /* Observable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5072C06726F6F6BBC8F424CF02DC72A6 /* Observable+Extensions.swift */; }; + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = C388C43D710EB98A12A3D12392B65966 /* Request.swift */; }; + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + F2246690EA6DEBF52D4CACA089B7FFC0 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FDC5A55577302E9CFDD8B281E7306A8 /* LockOwnerType.swift */; }; + F460F46DBA5EE0D4FABB3CD0BEFE6CE3 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C741C2F01B589E038E057B8A69C5B94 /* Debug.swift */; }; + FEDA6187E5CC1CFB1781F8F4947E160C /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9C32ACEEF17B06C853D4825FE474E5B /* ConcurrentMainScheduler.swift */; }; + FFDD18622776D270EAFE1CF94726C96D /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E14C64967507CA6DC6DA566986CD17F2 /* VirtualTimeScheduler.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 1B1D2D2B5F790067C63584DC46E8DEED /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; + remoteInfo = Alamofire; + }; + 1E7EDC9660FD64A123EAC6BDA4C055AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = F316854D76F084E9539BFEF85DCBCF9D; + remoteInfo = RxSwift; + }; + 80996B8BB3446668F158E7817336A6E4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; + remoteInfo = Alamofire; + }; + C11AB97FC44865EAFD37FD7629B96B72 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = F316854D76F084E9539BFEF85DCBCF9D; + remoteInfo = RxSwift; + }; + D6508A8A1DB5D04976ECA9641101DB50 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = B3F4219972B712BDBD25392781A43848; + remoteInfo = PetstoreClient; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0038480FC536F454DACB4DBE1E10094B /* Zip+CollectionType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+CollectionType.swift"; path = "RxSwift/Observables/Implementations/Zip+CollectionType.swift"; sourceTree = ""; }; + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 00BA2EEB61EC81F2780197C863C8E05B /* ConnectableObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservable.swift; path = RxSwift/Observables/Implementations/ConnectableObservable.swift; sourceTree = ""; }; + 013B18D5D7BF1208DB3103CFB973DCD6 /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + 0166A36C1ECFD7F42214A2DFF894A89E /* RxSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.xcconfig; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 032DA67F177D4161CBEB8BD61FA17071 /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Implementations/Skip.swift; sourceTree = ""; }; + 039008973BB72A292E730497A11A8863 /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Implementations/Sequence.swift; sourceTree = ""; }; + 04278C1CC34204EF9733A22C2EA2FD0F /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Implementations/Producer.swift; sourceTree = ""; }; + 04443F5A669B9694BEF5EB3BE6BAAE07 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 08411B5538F3A7C67CFF13F4C5EF3B2A /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + 0B2DD91E9F30A7E4967B6A344D389C44 /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Implementations/Window.swift; sourceTree = ""; }; + 0C9E156C15F63A992E8CB37F9A50E6D1 /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + 0D29DC2DC35087E0FB07AE49D5D693C1 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 107044D71C2AC150AAF28FD7DBC5BE35 /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Implementations/Sample.swift; sourceTree = ""; }; + 10CB3D5DB99AC32CF878965519F3B41B /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Implementations/Timer.swift; sourceTree = ""; }; + 124CDC65B696C8DC861A12328CC0F15E /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + 12C5111A9F88E244A38CA56C1276C125 /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Implementations/Throttle.swift; sourceTree = ""; }; + 14ACCC553ABB39FB00F047DA250ED44C /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 174587C7E166EDD81F62A533BF855010 /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Implementations/Scan.swift; sourceTree = ""; }; + 185BAC8C4C600A1E781B848207964435 /* TakeUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeUntil.swift; path = RxSwift/Observables/Implementations/TakeUntil.swift; sourceTree = ""; }; + 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 1A5B195ED13C7B5812C1C19D9A0AF4E7 /* Observable+Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Debug.swift"; path = "RxSwift/Observables/Observable+Debug.swift"; sourceTree = ""; }; + 1C608FA6A7556229DA9A86262C5293DC /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = RxSwift.modulemap; sourceTree = ""; }; + 1CAD5539CBA152B38C00AA245AB29284 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = RxSwift/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 1CB5D30407CA9653D9CCF2F93C2B5CB9 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = RxSwift/Platform/Platform.Linux.swift; sourceTree = ""; }; + 1CB77666BCB3637056A25CE3EBA0F469 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 1CD5B3237A6E093FFA4F2997C134F2DD /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/Implementations/AddRef.swift; sourceTree = ""; }; + 1DE7502D330E44C08B1F7A81D8F56963 /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + 1F9414D2D4412FCB719C37DB1F9A122B /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + 209AA17DAFB4137150A4B269C8D61D46 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + 21174758D397BBC916241AFE05CDC8A8 /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/Implementations/StartWith.swift; sourceTree = ""; }; + 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + 236369DA7426FBB45E8EDCC452D29C35 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 24716D0E21B0DC160D43515DCC16DABE /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = RxSwift/DataStructures/Bag.swift; sourceTree = ""; }; + 25F2A92C679F5078F32A8C93C4046870 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 2607E6E8AFF3EECBB571B72B0D1F59CF /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 26DC12270A3810F7571A22ADA1B2E3C3 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Implementations/Multicast.swift; sourceTree = ""; }; + 26E73BA869E104BC817E6A4EE0F6BFFE /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Implementations/Switch.swift; sourceTree = ""; }; + 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + 28A18D960F2A71740B74380466850EFA /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2BCFEBA50D572B696909D7D41BAB79AB /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Implementations/Buffer.swift; sourceTree = ""; }; + 2E29B122E21967769A1A67483CF0E9B3 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Implementations/Map.swift; sourceTree = ""; }; + 2E8FB7417C3CF49AE4BB883A3D0B1701 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 2FD520A0B67F84361BFA33C7418244A3 /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/Implementations/DistinctUntilChanged.swift; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; + 307A5528A2C4C2361F08E104A787F806 /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 315C6F02302A95859FB437750811D16C /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 349A4282992FE83BD930BDE9553299B9 /* ShareReplay1WhileConnected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplay1WhileConnected.swift; path = RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift; sourceTree = ""; }; + 3882A5E8DEB676D211220F11769089C3 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + 3A372EE18837587E94712F2D33A5A25F /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/Implementations/ObserveOn.swift; sourceTree = ""; }; + 3CEE4BCEFD46808967A306CE2FE52BE7 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 3D7D5684003E0341A47DFDC1F5ADEDE4 /* Observable+Aggregate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Aggregate.swift"; path = "RxSwift/Observables/Observable+Aggregate.swift"; sourceTree = ""; }; + 3E3482AC7A6F3044A3B7F9F260FACCE4 /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 3EB91AB4E00273BC81BDB9A8724669F2 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Implementations/Deferred.swift; sourceTree = ""; }; + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 3FA4C042B453E02311BC876D6F21BDE7 /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/Implementations/SingleAsync.swift; sourceTree = ""; }; + 417B31FE938008356C6948F57BCE692B /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + 41CE3CC9A5CC39149C281EE98E90DD06 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Implementations/Generate.swift; sourceTree = ""; }; + 4394A584E7D89F9FB5B789CB755067DC /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + 44F2ACF7E9C031E03B07A7BBAC875B7F /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 47A47359019C20FADB3204C4ACD9E332 /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Implementations/Zip.swift; sourceTree = ""; }; + 48CCF08CD6920361C24CF3A22A56A7AC /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/Implementations/TakeLast.swift; sourceTree = ""; }; + 491C7768EB60DF34EA12C24849C2D72F /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Implementations/Error.swift; sourceTree = ""; }; + 4A29FE9D0351954C77F9749A80112D24 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + 4B8CDA72BC4EB0297E6B427528093D09 /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + 4B90561BFCE4E31D197F5EEDD205617F /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = RxSwift/DataStructures/Queue.swift; sourceTree = ""; }; + 4CF09B7E555E5751AA869EE6A419F9E8 /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + 5072C06726F6F6BBC8F424CF02DC72A6 /* Observable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Extensions.swift"; path = "RxSwift/Observable+Extensions.swift"; sourceTree = ""; }; + 50D58CB31D4E74CF5CC37D60F68B493A /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/Implementations/ToArray.swift; sourceTree = ""; }; + 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 54CD9FADE39EF69EAD6845394C0B31B4 /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 54FB4EAB8FE7EB1FAAF54C2CD669407F /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 55D3D677F8A9120F4F8A7640855EF664 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 577931910F552C8D583E4F06297AE5F0 /* Observable+Creation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Creation.swift"; path = "RxSwift/Observables/Observable+Creation.swift"; sourceTree = ""; }; + 58BDB15E6DB9E373B0AD0499AFC07284 /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + 58D0E9FFEEC555EF3D53C7FEB94A90AF /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 5992242BCBCCD7195DCB2E5DD5AAF03F /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Implementations/Repeat.swift; sourceTree = ""; }; + 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 60057AA4C3D045344B41F9CBFBE2F8D3 /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + 6225D2C450CDCF3D7A748BA49E45B97D /* RefCount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCount.swift; path = RxSwift/Observables/Implementations/RefCount.swift; sourceTree = ""; }; + 62716568919652C42C9CE8CE08BA1BC1 /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Implementations/Timeout.swift; sourceTree = ""; }; + 6564B4424B5F7C755C24BD43C38EC5E5 /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Implementations/Take.swift; sourceTree = ""; }; + 6674B43168347A74679915BC8E23CEEB /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + 6786D5EBEC19CE47B39AAA29EF60C40D /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Implementations/Do.swift; sourceTree = ""; }; + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 68C7B45B8F12061A28461A80B8BCF3CD /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + 69756B9C78B48FF74CD369EFCDE9C2B1 /* Observable+Time.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Time.swift"; path = "RxSwift/Observables/Observable+Time.swift"; sourceTree = ""; }; + 69E4AF865DEA1313D953D5D999EB66D9 /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + 6A1DFDC8C172C170471AD51E8387245D /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + 6C741C2F01B589E038E057B8A69C5B94 /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Implementations/Debug.swift; sourceTree = ""; }; + 6F3BD79A2222142FAFB325DA25C25B93 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + 70C9C312AA84856756C184379F21100D /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 71BBD80B0287AD0696ECFB9E594CC1A1 /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/Implementations/CombineLatest+arity.swift"; sourceTree = ""; }; + 72E00C987CFA33BA8118B62116109E5C /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 74EC64ED13811CA9471CD3CE2ECE0B62 /* Observable+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Concurrency.swift"; path = "RxSwift/Observables/Observable+Concurrency.swift"; sourceTree = ""; }; + 7710661431185B0AF05251F7C5C5B6B3 /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 7766171C5E635B853B5374F01544B689 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + 79FB4FB8DD0A8BFD4AEDF7FC691EA462 /* Observable+StandardSequenceOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+StandardSequenceOperators.swift"; path = "RxSwift/Observables/Observable+StandardSequenceOperators.swift"; sourceTree = ""; }; + 7A3CC2759B818468C801A6873787A57F /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 7C02D69889BAB0CD549F6E8B7AB1E906 /* SynchronizedSubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedSubscribeType.swift; path = RxSwift/Concurrency/SynchronizedSubscribeType.swift; sourceTree = ""; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 801E5BB24BC33733C0DB65AD5D8184D3 /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + 833063D9EDB0A6FDC729B019C944CC81 /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Implementations/Sink.swift; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 871187CA85FEE565F015ABAE28232F63 /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Implementations/Reduce.swift; sourceTree = ""; }; + 8786CF728CE1174F80409B6D56DEF6BD /* NAryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NAryDisposable.swift; path = RxSwift/Disposables/NAryDisposable.swift; sourceTree = ""; }; + 8910C8F9A813CED4DAA22900102E6B35 /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Implementations/Using.swift; sourceTree = ""; }; + 893CB8DCF25ADBB99031B207B1A6C6D7 /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + 8A076FA46214932ED98BF355FD36239A /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + 8CF9A02E2D7DB5CB8F88A2B416E845CE /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 8D3AF641ABBC688B16196427A4F87AC9 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 8F447156B743BC57A765F3E625485703 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + 8FDC5A55577302E9CFDD8B281E7306A8 /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + 91023257BB0F8F89168BED72C9D18A04 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 95805B1F937B0B277A4436B1CC9D36A8 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Implementations/Empty.swift; sourceTree = ""; }; + 9610BA4403551C05999CF892D495F516 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 96A79AA09F5647BD1FF7A9E49D5DA5C3 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 99127A798646251A08D12F15E0848F88 /* StableCompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StableCompositeDisposable.swift; path = RxSwift/Disposables/StableCompositeDisposable.swift; sourceTree = ""; }; + 9AD198F0512985543E25A9FBDD7D6BC7 /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + 9C3336183F2A5A748C53087E6C5CCB26 /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + 9CB6241FE221077DEEAFBF12B7662DE3 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 9D8BAB1F0D14E7FAEB9A041AD0DE312D /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9F0A02687B1778ABBE05DC52DD87D428 /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/Implementations/SubscribeOn.swift; sourceTree = ""; }; + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + A04C65CAE7ECACBA7F91B893BF515EC3 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + A1ED40A755F10A4696EA0CBB2D7FEE85 /* AnonymousInvocable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousInvocable.swift; path = RxSwift/Schedulers/Internal/AnonymousInvocable.swift; sourceTree = ""; }; + A728EA00016FD91834126F5AEA1E3A9D /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = RxSwift/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + A85785AC2F7131137CEC1AA518A99821 /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AE4B2A92C93C96C8B19538C86BF4C9B3 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + B01AD6F6AA11897970B6FF1F85239450 /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/Implementations/SkipWhile.swift; sourceTree = ""; }; + B075E56C75F06E89FF786E9497A7BF1D /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + B1CBDF4BE3A5447A1A092129A27CB712 /* Observable+Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Single.swift"; path = "RxSwift/Observables/Observable+Single.swift"; sourceTree = ""; }; + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B3E50C8032DD5CE4271A38EA13EC1B7E /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + B50291BA734D2D01C64FD306DE8755C9 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + B59F044C2F3AA0F88DA1E524A6E19DAD /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/Implementations/SkipUntil.swift; sourceTree = ""; }; + B67FE3B78F251062560D5B54332F8488 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + C00667BAC6E66709B455A4791117BB57 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + C388C43D710EB98A12A3D12392B65966 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + C3B3267FBF371A572A0D8E8CA180C4C1 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C50A6F0BDAFC21594FAFC3C626AFD1D2 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + C75D367A5167A68A60279B4218AC83C6 /* CombineLatest+CollectionType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+CollectionType.swift"; path = "RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift"; sourceTree = ""; }; + C92F3601F527E23AF6A2887AABB8A93F /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = RxSwift/Platform/Platform.Darwin.swift; sourceTree = ""; }; + C9C32ACEEF17B06C853D4825FE474E5B /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + CA4EB37CDC7CB7862DFA4AB2A4F30266 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Implementations/Filter.swift; sourceTree = ""; }; + CB8353298303C7BF494403F3677F02B7 /* Observable+Multiple.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Multiple.swift"; path = "RxSwift/Observables/Observable+Multiple.swift"; sourceTree = ""; }; + CC62C1534DF3C33EADA5A490B5AE9CDA /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/Implementations/DelaySubscription.swift; sourceTree = ""; }; + CE40AF57E15052EF477B40E33879F683 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/Implementations/ElementAt.swift; sourceTree = ""; }; + CEB263E7AF9CDED7D6E05CE40D939240 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + CEDBB4F4415D38EEFF0B0532A8AB6D2E /* String+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Rx.swift"; path = "RxSwift/Extensions/String+Rx.swift"; sourceTree = ""; }; + CF11B71848EE4F7F9EB65BD8619E9F34 /* TakeWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWhile.swift; path = RxSwift/Observables/Implementations/TakeWhile.swift; sourceTree = ""; }; + D13D4B9C215DA186C0A3E5B1932B3D29 /* Variable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Variable.swift; path = RxSwift/Subjects/Variable.swift; sourceTree = ""; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + D47AC1CB336615BAAC40EEC13860795D /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Implementations/Catch.swift; sourceTree = ""; }; + D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + D4F3C53CFE3E02A3D827152998ED3269 /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + D96789E22AD200745F369A8171A18AE9 /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/Implementations/CombineLatest.swift; sourceTree = ""; }; + DAD7CCDEF0C0B768218C2662276F4902 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Implementations/Merge.swift; sourceTree = ""; }; + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DE12CC67B55FF5D86267EFF452D23F58 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + DEE22BA1BE31E7D0A0B5BF1B464EF7CC /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/Implementations/WithLatestFrom.swift; sourceTree = ""; }; + E14C64967507CA6DC6DA566986CD17F2 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + E20497D5F106B70BA10AFEB21CA855FA /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; + E449EE7665AC03F6CB4C69C078A2C6E1 /* AnonymousObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObservable.swift; path = RxSwift/Observables/Implementations/AnonymousObservable.swift; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E5ACFE2C40780B40C48574E06FA048AE /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + E6403ECBAB24559C81D937984B72A3A7 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + E6EAA1E1ACF9BD144EB4E8FF2EB56C8C /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + E7A677E2624A679FA6A7B5E795BB5B04 /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + E884CFDBB07F3CB079CE908979ECB598 /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Implementations/Never.swift; sourceTree = ""; }; + E8E8FBD5D0739C97C372A6073AC616EE /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Implementations/Concat.swift; sourceTree = ""; }; + E9B8E0AD4CAA3B322ABD3B211D352E49 /* ImmediateScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateScheduler.swift; path = RxSwift/Schedulers/ImmediateScheduler.swift; sourceTree = ""; }; + E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + EA1D3C1000B643672DC644FD0CBE24A8 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + EA3CFBEC085617E86B78D9C8DCA19F82 /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + EB4CC27373795992C949EB261869D25D /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Implementations/Just.swift; sourceTree = ""; }; + EBCA5397A4618572E794E81BBBAF486B /* DispatchQueueSchedulerQOS.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueSchedulerQOS.swift; path = RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift; sourceTree = ""; }; + EBF34B9E74264B0313658E8FC445AF7C /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + EF45CBC0BB14D377AE86709A7C9BB7E0 /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Implementations/Amb.swift; sourceTree = ""; }; + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F17674406359B17ECA62D6F4F62CE140 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + F1A81E73C3EA60E53695BDA2B8A16A92 /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + F1B8553865AA7FC5E48F0EFCC43EF1E5 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Implementations/Range.swift; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F5663B56546A40CF4D9DC4E08F05CF9A /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/Implementations/RetryWhen.swift; sourceTree = ""; }; + F5CDD03686D25AF1BF04A28DBB0D83D2 /* ShareReplay1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplay1.swift; path = RxSwift/Observables/Implementations/ShareReplay1.swift; sourceTree = ""; }; + F7318F7B1BEFE5935B6F3D1208C7A07D /* ObserveOnSerialDispatchQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOnSerialDispatchQueue.swift; path = RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift; sourceTree = ""; }; + F9B46E628DE07A2596AD75B742E148BC /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Implementations/Zip+arity.swift"; sourceTree = ""; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; + FE5C8F881BB25EDFF298416A85915112 /* Observable+Binding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Binding.swift"; path = "RxSwift/Observables/Observable+Binding.swift"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 05BA91ABD8AC918A49A9D7E0E3722C70 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 14DD51004DF8C27A7D0491AEFEC5F464 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 76130794E62D45206C62CE83429B6CF2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9FDB94097AD437CDE44A507037AE4010 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CB2482011FA929C2BCC3E41A1B6E02E1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 110E6B43666A729745E9980F080944C4 /* Alamofire.framework in Frameworks */, + 393372CC0F931D0D192179C4B16DF65E /* Foundation.framework in Frameworks */, + 58344FE826FA6ED012A3450ACB0BF93D /* RxSwift.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { + isa = PBXGroup; + children = ( + D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */, + 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */, + 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */, + 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */, + 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */, + ); + path = Models; + sourceTree = ""; + }; + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { + isa = PBXGroup; + children = ( + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + 23250983C15892960D4F263BCF5E8150 /* RxSwift */ = { + isa = PBXGroup; + children = ( + 1CD5B3237A6E093FFA4F2997C134F2DD /* AddRef.swift */, + EF45CBC0BB14D377AE86709A7C9BB7E0 /* Amb.swift */, + 1DE7502D330E44C08B1F7A81D8F56963 /* AnonymousDisposable.swift */, + A1ED40A755F10A4696EA0CBB2D7FEE85 /* AnonymousInvocable.swift */, + E449EE7665AC03F6CB4C69C078A2C6E1 /* AnonymousObservable.swift */, + A04C65CAE7ECACBA7F91B893BF515EC3 /* AnonymousObserver.swift */, + 4A29FE9D0351954C77F9749A80112D24 /* AnyObserver.swift */, + 801E5BB24BC33733C0DB65AD5D8184D3 /* AsyncLock.swift */, + 24716D0E21B0DC160D43515DCC16DABE /* Bag.swift */, + 9AD198F0512985543E25A9FBDD7D6BC7 /* BehaviorSubject.swift */, + E5ACFE2C40780B40C48574E06FA048AE /* BinaryDisposable.swift */, + E6EAA1E1ACF9BD144EB4E8FF2EB56C8C /* BooleanDisposable.swift */, + 2BCFEBA50D572B696909D7D41BAB79AB /* Buffer.swift */, + B67FE3B78F251062560D5B54332F8488 /* Cancelable.swift */, + D47AC1CB336615BAAC40EEC13860795D /* Catch.swift */, + D96789E22AD200745F369A8171A18AE9 /* CombineLatest.swift */, + 71BBD80B0287AD0696ECFB9E594CC1A1 /* CombineLatest+arity.swift */, + C75D367A5167A68A60279B4218AC83C6 /* CombineLatest+CollectionType.swift */, + 69E4AF865DEA1313D953D5D999EB66D9 /* CompositeDisposable.swift */, + E8E8FBD5D0739C97C372A6073AC616EE /* Concat.swift */, + F17674406359B17ECA62D6F4F62CE140 /* ConcurrentDispatchQueueScheduler.swift */, + C9C32ACEEF17B06C853D4825FE474E5B /* ConcurrentMainScheduler.swift */, + 00BA2EEB61EC81F2780197C863C8E05B /* ConnectableObservable.swift */, + 124CDC65B696C8DC861A12328CC0F15E /* ConnectableObservableType.swift */, + 68C7B45B8F12061A28461A80B8BCF3CD /* CurrentThreadScheduler.swift */, + 6C741C2F01B589E038E057B8A69C5B94 /* Debug.swift */, + 3EB91AB4E00273BC81BDB9A8724669F2 /* Deferred.swift */, + CC62C1534DF3C33EADA5A490B5AE9CDA /* DelaySubscription.swift */, + EBCA5397A4618572E794E81BBBAF486B /* DispatchQueueSchedulerQOS.swift */, + 60057AA4C3D045344B41F9CBFBE2F8D3 /* Disposable.swift */, + 58D0E9FFEEC555EF3D53C7FEB94A90AF /* DisposeBag.swift */, + 54FB4EAB8FE7EB1FAAF54C2CD669407F /* DisposeBase.swift */, + 2FD520A0B67F84361BFA33C7418244A3 /* DistinctUntilChanged.swift */, + 6786D5EBEC19CE47B39AAA29EF60C40D /* Do.swift */, + CE40AF57E15052EF477B40E33879F683 /* ElementAt.swift */, + 95805B1F937B0B277A4436B1CC9D36A8 /* Empty.swift */, + 491C7768EB60DF34EA12C24849C2D72F /* Error.swift */, + 7766171C5E635B853B5374F01544B689 /* Errors.swift */, + EA3CFBEC085617E86B78D9C8DCA19F82 /* Event.swift */, + CA4EB37CDC7CB7862DFA4AB2A4F30266 /* Filter.swift */, + 41CE3CC9A5CC39149C281EE98E90DD06 /* Generate.swift */, + EA1D3C1000B643672DC644FD0CBE24A8 /* HistoricalScheduler.swift */, + 72E00C987CFA33BA8118B62116109E5C /* HistoricalSchedulerTimeConverter.swift */, + E9B8E0AD4CAA3B322ABD3B211D352E49 /* ImmediateScheduler.swift */, + 6F3BD79A2222142FAFB325DA25C25B93 /* ImmediateSchedulerType.swift */, + A728EA00016FD91834126F5AEA1E3A9D /* InfiniteSequence.swift */, + 8A076FA46214932ED98BF355FD36239A /* InvocableScheduledItem.swift */, + E20497D5F106B70BA10AFEB21CA855FA /* InvocableType.swift */, + EB4CC27373795992C949EB261869D25D /* Just.swift */, + B075E56C75F06E89FF786E9497A7BF1D /* Lock.swift */, + 8FDC5A55577302E9CFDD8B281E7306A8 /* LockOwnerType.swift */, + 2607E6E8AFF3EECBB571B72B0D1F59CF /* MainScheduler.swift */, + 2E29B122E21967769A1A67483CF0E9B3 /* Map.swift */, + DAD7CCDEF0C0B768218C2662276F4902 /* Merge.swift */, + 26DC12270A3810F7571A22ADA1B2E3C3 /* Multicast.swift */, + 8786CF728CE1174F80409B6D56DEF6BD /* NAryDisposable.swift */, + E884CFDBB07F3CB079CE908979ECB598 /* Never.swift */, + 893CB8DCF25ADBB99031B207B1A6C6D7 /* NopDisposable.swift */, + 54CD9FADE39EF69EAD6845394C0B31B4 /* Observable.swift */, + 3D7D5684003E0341A47DFDC1F5ADEDE4 /* Observable+Aggregate.swift */, + FE5C8F881BB25EDFF298416A85915112 /* Observable+Binding.swift */, + 74EC64ED13811CA9471CD3CE2ECE0B62 /* Observable+Concurrency.swift */, + 577931910F552C8D583E4F06297AE5F0 /* Observable+Creation.swift */, + 1A5B195ED13C7B5812C1C19D9A0AF4E7 /* Observable+Debug.swift */, + 5072C06726F6F6BBC8F424CF02DC72A6 /* Observable+Extensions.swift */, + CB8353298303C7BF494403F3677F02B7 /* Observable+Multiple.swift */, + B1CBDF4BE3A5447A1A092129A27CB712 /* Observable+Single.swift */, + 79FB4FB8DD0A8BFD4AEDF7FC691EA462 /* Observable+StandardSequenceOperators.swift */, + 69756B9C78B48FF74CD369EFCDE9C2B1 /* Observable+Time.swift */, + E7A677E2624A679FA6A7B5E795BB5B04 /* ObservableConvertibleType.swift */, + 58BDB15E6DB9E373B0AD0499AFC07284 /* ObservableType.swift */, + 3A372EE18837587E94712F2D33A5A25F /* ObserveOn.swift */, + F7318F7B1BEFE5935B6F3D1208C7A07D /* ObserveOnSerialDispatchQueue.swift */, + 91023257BB0F8F89168BED72C9D18A04 /* ObserverBase.swift */, + 209AA17DAFB4137150A4B269C8D61D46 /* ObserverType.swift */, + DE12CC67B55FF5D86267EFF452D23F58 /* OperationQueueScheduler.swift */, + C92F3601F527E23AF6A2887AABB8A93F /* Platform.Darwin.swift */, + 1CB5D30407CA9653D9CCF2F93C2B5CB9 /* Platform.Linux.swift */, + 1CAD5539CBA152B38C00AA245AB29284 /* PriorityQueue.swift */, + 04278C1CC34204EF9733A22C2EA2FD0F /* Producer.swift */, + B3E50C8032DD5CE4271A38EA13EC1B7E /* PublishSubject.swift */, + 4B90561BFCE4E31D197F5EEDD205617F /* Queue.swift */, + F1B8553865AA7FC5E48F0EFCC43EF1E5 /* Range.swift */, + 8F447156B743BC57A765F3E625485703 /* RecursiveScheduler.swift */, + 871187CA85FEE565F015ABAE28232F63 /* Reduce.swift */, + 6225D2C450CDCF3D7A748BA49E45B97D /* RefCount.swift */, + F1A81E73C3EA60E53695BDA2B8A16A92 /* RefCountDisposable.swift */, + 5992242BCBCCD7195DCB2E5DD5AAF03F /* Repeat.swift */, + 3E3482AC7A6F3044A3B7F9F260FACCE4 /* ReplaySubject.swift */, + F5663B56546A40CF4D9DC4E08F05CF9A /* RetryWhen.swift */, + 4394A584E7D89F9FB5B789CB755067DC /* Rx.swift */, + 6A1DFDC8C172C170471AD51E8387245D /* RxMutableBox.swift */, + 107044D71C2AC150AAF28FD7DBC5BE35 /* Sample.swift */, + 174587C7E166EDD81F62A533BF855010 /* Scan.swift */, + 307A5528A2C4C2361F08E104A787F806 /* ScheduledDisposable.swift */, + 3882A5E8DEB676D211220F11769089C3 /* ScheduledItem.swift */, + 70C9C312AA84856756C184379F21100D /* ScheduledItemType.swift */, + EBF34B9E74264B0313658E8FC445AF7C /* SchedulerServices+Emulation.swift */, + 9C3336183F2A5A748C53087E6C5CCB26 /* SchedulerType.swift */, + 039008973BB72A292E730497A11A8863 /* Sequence.swift */, + 7710661431185B0AF05251F7C5C5B6B3 /* SerialDispatchQueueScheduler.swift */, + 013B18D5D7BF1208DB3103CFB973DCD6 /* SerialDisposable.swift */, + F5CDD03686D25AF1BF04A28DBB0D83D2 /* ShareReplay1.swift */, + 349A4282992FE83BD930BDE9553299B9 /* ShareReplay1WhileConnected.swift */, + 4B8CDA72BC4EB0297E6B427528093D09 /* SingleAssignmentDisposable.swift */, + 3FA4C042B453E02311BC876D6F21BDE7 /* SingleAsync.swift */, + 833063D9EDB0A6FDC729B019C944CC81 /* Sink.swift */, + 032DA67F177D4161CBEB8BD61FA17071 /* Skip.swift */, + B59F044C2F3AA0F88DA1E524A6E19DAD /* SkipUntil.swift */, + B01AD6F6AA11897970B6FF1F85239450 /* SkipWhile.swift */, + 99127A798646251A08D12F15E0848F88 /* StableCompositeDisposable.swift */, + 21174758D397BBC916241AFE05CDC8A8 /* StartWith.swift */, + CEDBB4F4415D38EEFF0B0532A8AB6D2E /* String+Rx.swift */, + 6674B43168347A74679915BC8E23CEEB /* SubjectType.swift */, + 9F0A02687B1778ABBE05DC52DD87D428 /* SubscribeOn.swift */, + 315C6F02302A95859FB437750811D16C /* SubscriptionDisposable.swift */, + 26E73BA869E104BC817E6A4EE0F6BFFE /* Switch.swift */, + 0C9E156C15F63A992E8CB37F9A50E6D1 /* SynchronizedDisposeType.swift */, + D4F3C53CFE3E02A3D827152998ED3269 /* SynchronizedOnType.swift */, + 7C02D69889BAB0CD549F6E8B7AB1E906 /* SynchronizedSubscribeType.swift */, + 28A18D960F2A71740B74380466850EFA /* SynchronizedUnsubscribeType.swift */, + A85785AC2F7131137CEC1AA518A99821 /* TailRecursiveSink.swift */, + 6564B4424B5F7C755C24BD43C38EC5E5 /* Take.swift */, + 48CCF08CD6920361C24CF3A22A56A7AC /* TakeLast.swift */, + 185BAC8C4C600A1E781B848207964435 /* TakeUntil.swift */, + CF11B71848EE4F7F9EB65BD8619E9F34 /* TakeWhile.swift */, + 12C5111A9F88E244A38CA56C1276C125 /* Throttle.swift */, + 62716568919652C42C9CE8CE08BA1BC1 /* Timeout.swift */, + 10CB3D5DB99AC32CF878965519F3B41B /* Timer.swift */, + 50D58CB31D4E74CF5CC37D60F68B493A /* ToArray.swift */, + 8910C8F9A813CED4DAA22900102E6B35 /* Using.swift */, + D13D4B9C215DA186C0A3E5B1932B3D29 /* Variable.swift */, + 3CEE4BCEFD46808967A306CE2FE52BE7 /* VirtualTimeConverterType.swift */, + E14C64967507CA6DC6DA566986CD17F2 /* VirtualTimeScheduler.swift */, + 0B2DD91E9F30A7E4967B6A344D389C44 /* Window.swift */, + DEE22BA1BE31E7D0A0B5BF1B464EF7CC /* WithLatestFrom.swift */, + 47A47359019C20FADB3204C4ACD9E332 /* Zip.swift */, + F9B46E628DE07A2596AD75B742E148BC /* Zip+arity.swift */, + 0038480FC536F454DACB4DBE1E10094B /* Zip+CollectionType.swift */, + AFA7CBE8A9A163EC18383592AF66F191 /* Support Files */, + ); + path = RxSwift; + sourceTree = ""; + }; + 5E2543AE40E062857224EB1DCE80B9E3 /* iOS */ = { + isa = PBXGroup; + children = ( + 9610BA4403551C05999CF892D495F516 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 69750F9014CEFA9B29584C65B2491D2E /* Frameworks */ = { + isa = PBXGroup; + children = ( + AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */, + 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */, + 5E2543AE40E062857224EB1DCE80B9E3 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + 69750F9014CEFA9B29584C65B2491D2E /* Frameworks */, + AF18CF0DA9CD0027FE9BDB69AD02D6B5 /* Pods */, + C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { + isa = PBXGroup; + children = ( + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { + isa = PBXGroup; + children = ( + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */, + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */, + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */, + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */, + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */, + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + 9ED03EE02142D90FE6AF289DCA4A50C1 /* Support Files */ = { + isa = PBXGroup; + children = ( + 25F2A92C679F5078F32A8C93C4046870 /* Alamofire.modulemap */, + E6403ECBAB24559C81D937984B72A3A7 /* Alamofire.xcconfig */, + 1CB77666BCB3637056A25CE3EBA0F469 /* Alamofire-dummy.m */, + 7A3CC2759B818468C801A6873787A57F /* Alamofire-prefix.pch */, + C50A6F0BDAFC21594FAFC3C626AFD1D2 /* Alamofire-umbrella.h */, + 55D3D677F8A9120F4F8A7640855EF664 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { + isa = PBXGroup; + children = ( + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, + ); + path = Classes; + sourceTree = ""; + }; + AF18CF0DA9CD0027FE9BDB69AD02D6B5 /* Pods */ = { + isa = PBXGroup; + children = ( + C4161B38AA0E2FC553F8ACD3B652932C /* Alamofire */, + 23250983C15892960D4F263BCF5E8150 /* RxSwift */, + ); + name = Pods; + sourceTree = ""; + }; + AFA7CBE8A9A163EC18383592AF66F191 /* Support Files */ = { + isa = PBXGroup; + children = ( + 9D8BAB1F0D14E7FAEB9A041AD0DE312D /* Info.plist */, + 1C608FA6A7556229DA9A86262C5293DC /* RxSwift.modulemap */, + 0166A36C1ECFD7F42214A2DFF894A89E /* RxSwift.xcconfig */, + 4CF09B7E555E5751AA869EE6A419F9E8 /* RxSwift-dummy.m */, + C3B3267FBF371A572A0D8E8CA180C4C1 /* RxSwift-prefix.pch */, + 417B31FE938008356C6948F57BCE692B /* RxSwift-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */ = { + isa = PBXGroup; + children = ( + 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */, + E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */, + 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */, + C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */, + 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */, + ); + name = Products; + sourceTree = ""; + }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + C4161B38AA0E2FC553F8ACD3B652932C /* Alamofire */ = { + isa = PBXGroup; + children = ( + 08411B5538F3A7C67CFF13F4C5EF3B2A /* Alamofire.swift */, + 2E8FB7417C3CF49AE4BB883A3D0B1701 /* Download.swift */, + 9CB6241FE221077DEEAFBF12B7662DE3 /* Error.swift */, + 1F9414D2D4412FCB719C37DB1F9A122B /* Manager.swift */, + 14ACCC553ABB39FB00F047DA250ED44C /* MultipartFormData.swift */, + 96A79AA09F5647BD1FF7A9E49D5DA5C3 /* NetworkReachabilityManager.swift */, + 04443F5A669B9694BEF5EB3BE6BAAE07 /* Notifications.swift */, + C00667BAC6E66709B455A4791117BB57 /* ParameterEncoding.swift */, + C388C43D710EB98A12A3D12392B65966 /* Request.swift */, + 8CF9A02E2D7DB5CB8F88A2B416E845CE /* Response.swift */, + 0D29DC2DC35087E0FB07AE49D5D693C1 /* ResponseSerialization.swift */, + 44F2ACF7E9C031E03B07A7BBAC875B7F /* Result.swift */, + AE4B2A92C93C96C8B19538C86BF4C9B3 /* ServerTrustPolicy.swift */, + B50291BA734D2D01C64FD306DE8755C9 /* Stream.swift */, + 236369DA7426FBB45E8EDCC452D29C35 /* Timeline.swift */, + 8D3AF641ABBC688B16196427A4F87AC9 /* Upload.swift */, + CEB263E7AF9CDED7D6E05CE40D939240 /* Validation.swift */, + 9ED03EE02142D90FE6AF289DCA4A50C1 /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */, + ); + path = PetstoreClient; + sourceTree = ""; + }; + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */, + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */, + ); + name = PetstoreClient; + path = ../..; + sourceTree = ""; + }; + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */ = { + isa = PBXGroup; + children = ( + 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */, + D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */, + D8072E1108951F272C003553FC8926C7 /* APIs.swift */, + 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */, + 8F0266C5AE0B23A436291F6647902086 /* Models.swift */, + F92EFB558CBA923AB1CFA22F708E315A /* APIs */, + 1322FED69118C64DAD026CAF7F4C38C6 /* Models */, + ); + path = Swaggers; + sourceTree = ""; + }; + F92EFB558CBA923AB1CFA22F708E315A /* APIs */ = { + isa = PBXGroup; + children = ( + 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */, + 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */, + 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */, + ); + path = APIs; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 0B076F0166D87A519E5251C471131E44 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 69AC467220269CE474E1C1156912C9DD /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99AE2032DA4A773DFF2E835A8D453117 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DFF7D509E6FC70067A71C1CF0441AD48 /* PetstoreClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9C8BBB69FE8BD651A7BBC07E32AED31A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 725EED04ED27CA8159CB2683F1EFD45A /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildPhases = ( + 0529825EC79AED06C77091DC0F061854 /* Sources */, + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, + FF84DA06E91FBBAA756A7832375803CE /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */; + productType = "com.apple.product-type.framework"; + }; + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + 7E04F4E0C9D1C499E7C5C2E0653893A5 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = C17E886D20DFCEDEFC84423D6652F7EE /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + EDDE9277BF55CC0EE317B81A0DB026A1 /* Sources */, + 05BA91ABD8AC918A49A9D7E0E3722C70 /* Frameworks */, + 9C8BBB69FE8BD651A7BBC07E32AED31A /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + C9B7EA4A29DBD0225CC347E19EBAC59F /* PBXTargetDependency */, + 31D9C92344926342E3D2800111C05269 /* PBXTargetDependency */, + 57DC5B1E798B66E24E2BEC74CDB6BDF2 /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */; + productType = "com.apple.product-type.framework"; + }; + B3F4219972B712BDBD25392781A43848 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = F609276975EA85CEC0F2AA47BE77CDBD /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + CABD7A5E996838E97D6AE9D1E4A47DE6 /* Sources */, + CB2482011FA929C2BCC3E41A1B6E02E1 /* Frameworks */, + 99AE2032DA4A773DFF2E835A8D453117 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 9351A33C64C743193D9663213D4582BD /* PBXTargetDependency */, + F461599241C7FC6B0184BF7BAAEF658C /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; + F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7335F4AA774EFBDED5B7673EF35FCF11 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + 26ED5385D63D1F6761BEF3EA5FAE7165 /* Sources */, + 76130794E62D45206C62CE83429B6CF2 /* Frameworks */, + 0B076F0166D87A519E5251C471131E44 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, + B3F4219972B712BDBD25392781A43848 /* PetstoreClient */, + 7E04F4E0C9D1C499E7C5C2E0653893A5 /* Pods-SwaggerClient */, + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, + F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 0529825EC79AED06C77091DC0F061854 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 26ED5385D63D1F6761BEF3EA5FAE7165 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 22C91CF507223CEE1A7E1302E912DC8B /* AddRef.swift in Sources */, + CD00FDDA48E9BC390530672F9F09D8CF /* Amb.swift in Sources */, + B22405A127912A4943AEFBDD57E7A267 /* AnonymousDisposable.swift in Sources */, + 84B93CFEFA6412E49988C92153998357 /* AnonymousInvocable.swift in Sources */, + 4F8D754FA3405C5B692B644166A0F02A /* AnonymousObservable.swift in Sources */, + 77D1DB57FAA744C6ECBA7242836D6479 /* AnonymousObserver.swift in Sources */, + 751E794A58F9FCB7738D4ED30D10DD19 /* AnyObserver.swift in Sources */, + ADC582F488BC636CC4292513053F6992 /* AsyncLock.swift in Sources */, + D190592C39D806474770AF30FCC4EF4E /* Bag.swift in Sources */, + 9543E1505CCD2189D86456DAA0D55A22 /* BehaviorSubject.swift in Sources */, + 4DB1B23F5FAF7C5E02520AFE08646AF2 /* BinaryDisposable.swift in Sources */, + 96A03A2C4325A59DE2B02913FE351815 /* BooleanDisposable.swift in Sources */, + A606E44DA4B92B1FFBA177125D55F6AA /* Buffer.swift in Sources */, + 8BDC4F0F424CA9A8190F28E7A02417A8 /* Cancelable.swift in Sources */, + 39F4B474510DFC1711DD2EF809EA101B /* Catch.swift in Sources */, + B0F20FEA2B9A800D016EF5B46EFDECE9 /* CombineLatest+arity.swift in Sources */, + 04509FBE687E186C45C9E2F78E6F6946 /* CombineLatest+CollectionType.swift in Sources */, + 99F6DFF51E7C238DF99CA788144C732A /* CombineLatest.swift in Sources */, + 00A528BBED5B1D5DF26B8ADE64C5B3F2 /* CompositeDisposable.swift in Sources */, + 3DAFF4DA4C977B85B5C5B35728001AF2 /* Concat.swift in Sources */, + 028C4C90CAA75222DAA6CA7B37F16A84 /* ConcurrentDispatchQueueScheduler.swift in Sources */, + FEDA6187E5CC1CFB1781F8F4947E160C /* ConcurrentMainScheduler.swift in Sources */, + 030667BEF4154402A2317126A893E459 /* ConnectableObservable.swift in Sources */, + 1CBCB4FF2C9CDB144871C2A0856EB44D /* ConnectableObservableType.swift in Sources */, + ECFCC7B806126EF7788D0DE094711905 /* CurrentThreadScheduler.swift in Sources */, + F460F46DBA5EE0D4FABB3CD0BEFE6CE3 /* Debug.swift in Sources */, + 434C2C5108A8B9EEA916566F7DB0EDF6 /* Deferred.swift in Sources */, + 5997C0F97BD6687648224D5C6442B862 /* DelaySubscription.swift in Sources */, + 956216483BCB853794F52B0292831E9C /* DispatchQueueSchedulerQOS.swift in Sources */, + E51F4BE281ADBC629708A4D131E9190C /* Disposable.swift in Sources */, + 98FA1CFF63A5E74A7DB3255DA60C1843 /* DisposeBag.swift in Sources */, + 58023FA401993154E36E604471265263 /* DisposeBase.swift in Sources */, + 3AAB4B14DB0A02456F909B482400C142 /* DistinctUntilChanged.swift in Sources */, + AF3E5D2CE5E3448DB881E0F40F2F334F /* Do.swift in Sources */, + 4A216C127342712EDE589085CBB58962 /* ElementAt.swift in Sources */, + 5BD263D28F10A84969A6521CA166957C /* Empty.swift in Sources */, + 92450B928E8001F2B28A80072611F4C1 /* Error.swift in Sources */, + 498A556404BCE59DD962113CD29165A0 /* Errors.swift in Sources */, + BB3A568E8ED6C1792B43708A36A66F3D /* Event.swift in Sources */, + D180CF545583D5DCDF770FBAA36F5DB0 /* Filter.swift in Sources */, + A67CCBFC004EF58E785FA7ED4A1B69B6 /* Generate.swift in Sources */, + 22C9E40BB4DFB30DAAFD8555EF69BC08 /* HistoricalScheduler.swift in Sources */, + 5C8C1A80AB947F293430868D52A910C2 /* HistoricalSchedulerTimeConverter.swift in Sources */, + A4FBC2BD1A93FA52B5C97E79CDB9302F /* ImmediateScheduler.swift in Sources */, + 55D355CC26824B52E1A7420802FB5DC5 /* ImmediateSchedulerType.swift in Sources */, + C3739BDF471B57AECC84085608EC9CE6 /* InfiniteSequence.swift in Sources */, + 207AB9AAE48F202AF774554ED7545D98 /* InvocableScheduledItem.swift in Sources */, + 26E95A382D3F6848E571EF506D91B1C1 /* InvocableType.swift in Sources */, + 0487B12B08D927162A20CB2A56A2D077 /* Just.swift in Sources */, + 72CF8071AF37B85C1DE763805C39A3AB /* Lock.swift in Sources */, + F2246690EA6DEBF52D4CACA089B7FFC0 /* LockOwnerType.swift in Sources */, + B590B3C59D3A327452D2532766F2F630 /* MainScheduler.swift in Sources */, + 0D6AD3708152BB59E38D5839A0B0377F /* Map.swift in Sources */, + 4266AE0D8F9A4FA69F408AAC9118320A /* Merge.swift in Sources */, + 5BDF0811AEFBD49A7DE4AF35DA3BD34F /* Multicast.swift in Sources */, + E16A421C7269D0E81CB5E59344E63391 /* NAryDisposable.swift in Sources */, + 2023E24B94C04CC05DDFB499ECA760FB /* Never.swift in Sources */, + 00D1D0E4C3E6F9EA952C2EDEF2C13DE9 /* NopDisposable.swift in Sources */, + 7A6597623E723E6F8350D2CA30A2CD9C /* Observable+Aggregate.swift in Sources */, + D99C59116FC2BC799C9C9DE4D0282EB9 /* Observable+Binding.swift in Sources */, + A0A18CB5F889D7C2F80D6024EA568BEA /* Observable+Concurrency.swift in Sources */, + 618251D2C3027F214154D2CDFE1900AB /* Observable+Creation.swift in Sources */, + 501A111A5AE07BC13E3265DB49EE0A1B /* Observable+Debug.swift in Sources */, + EE42701AD3887754AF7695978852957E /* Observable+Extensions.swift in Sources */, + 68614EDB167FFFA6FBEC851368044FB3 /* Observable+Multiple.swift in Sources */, + 731E6ACE4939DCE8F6AF47FA1A00D595 /* Observable+Single.swift in Sources */, + E61B26D220A1A27E3BE7AD3F9BE35C76 /* Observable+StandardSequenceOperators.swift in Sources */, + 165531B0C3FF4D343825C3DB0B79FD68 /* Observable+Time.swift in Sources */, + DA18B15A9632B7282CF91FE4771C0B60 /* Observable.swift in Sources */, + E315A5FF56451DF73C7FE3140D5E2C6C /* ObservableConvertibleType.swift in Sources */, + 2BEA24EE395DA16EFEBC08B8D450F00A /* ObservableType.swift in Sources */, + 6414AAC9ED1AD7417B005D50D04341F5 /* ObserveOn.swift in Sources */, + CF13D1D873436D3890EC7392DEDE0B3E /* ObserveOnSerialDispatchQueue.swift in Sources */, + 88CCC2ADA43F75CB4708A701F5031643 /* ObserverBase.swift in Sources */, + 8D3CD54E3BACC9DB116DDA2DC30420CF /* ObserverType.swift in Sources */, + CA4A98FD2226B57E5F59E0BA2E1A97EC /* OperationQueueScheduler.swift in Sources */, + 6007585CC5912D979404BDB047CD36C4 /* Platform.Darwin.swift in Sources */, + D4789D8318C97E380412D03C1C321A88 /* Platform.Linux.swift in Sources */, + AC265ECE8E2AF91D58A755022E7DF802 /* PriorityQueue.swift in Sources */, + 4CA85A5CF8897D7D46BC6D0D76C8189A /* Producer.swift in Sources */, + DB5B0A5C01527330DCD4CEF9740C7140 /* PublishSubject.swift in Sources */, + B754E33E17893DF35DECA754DE819A66 /* Queue.swift in Sources */, + D0F5068C6F5C0489E8A41A9912A09016 /* Range.swift in Sources */, + AD9D268210ED449C3BE591513FD0CFB8 /* RecursiveScheduler.swift in Sources */, + 07E83400AACF1430C5B3DF482167A0F1 /* Reduce.swift in Sources */, + 3ADB6687421BF63BCC8A8C8D62E0C4F2 /* RefCount.swift in Sources */, + 66D9046FEDE40E6732F8B3E090007268 /* RefCountDisposable.swift in Sources */, + 5B721FAF55FEDB8046F23843565833A2 /* Repeat.swift in Sources */, + B28CA824CA5CD903042D8A07E9C5950E /* ReplaySubject.swift in Sources */, + 0A5F6F590DCE147853B2E21487ABA4AA /* RetryWhen.swift in Sources */, + 437C3354F611D5412125ADF24F4FDEE1 /* Rx.swift in Sources */, + 1A11209BABC1DE84187BFAEA3E91602D /* RxMutableBox.swift in Sources */, + B33369A55E29C11FA5F5977B5A47F1D4 /* RxSwift-dummy.m in Sources */, + 0607BCCDD781FF7FFD3629BF4A8BAD23 /* Sample.swift in Sources */, + 107E73472222CFD28A8C640F332DA52A /* Scan.swift in Sources */, + 0268E70939A7BFBC91C0557D16DDD027 /* ScheduledDisposable.swift in Sources */, + 4EF8849290BCC9D36D8D75969F6753E7 /* ScheduledItem.swift in Sources */, + BC10CEE813861D2F71E501E2F06532AB /* ScheduledItemType.swift in Sources */, + 0AEB6185484DD9137068A40CE70D4B85 /* SchedulerServices+Emulation.swift in Sources */, + 23CA1BD96C4742DE71082211C8DBFF5F /* SchedulerType.swift in Sources */, + 7E6DD4CEE210B03B7E3A0F01A36A7624 /* Sequence.swift in Sources */, + A23E9C4262ED3ED9FF20A9E6E1FA2121 /* SerialDispatchQueueScheduler.swift in Sources */, + 4AE52A909A95E3E4A6DC2F48BD8FC758 /* SerialDisposable.swift in Sources */, + 85E0465919F9DC7C97DD593CB49BB5E0 /* ShareReplay1.swift in Sources */, + 7F8297BE677C9A67B915F044DB16C0BE /* ShareReplay1WhileConnected.swift in Sources */, + 12999CCB3E22F57CB230F85534EF6930 /* SingleAssignmentDisposable.swift in Sources */, + 3EE9F1D7EB9C05CB5821E18136EF812E /* SingleAsync.swift in Sources */, + 4C5244B7F2D69F1DFC083E31070E3B0F /* Sink.swift in Sources */, + 33393FE8FB3933A22617E02FA3FFA780 /* Skip.swift in Sources */, + 79F6454BBF28D094A211494E22A07327 /* SkipUntil.swift in Sources */, + B7DCF4199B0EEF4CB2FE0DFF23F99049 /* SkipWhile.swift in Sources */, + B45CADB404E006E0EA39D7239C81C64F /* StableCompositeDisposable.swift in Sources */, + E8CAB3FA190277C8E609F992A51EA9D2 /* StartWith.swift in Sources */, + 9C824A364077ED1458CEF9776F2FB44A /* String+Rx.swift in Sources */, + 04923B3851BD1F857A9B207EE9EC8CDB /* SubjectType.swift in Sources */, + DC9EF51CEA903F88D43F7B3A96923DFD /* SubscribeOn.swift in Sources */, + CDF08B0C84BE839E79DF99C271453406 /* SubscriptionDisposable.swift in Sources */, + 3200EF8FA76EE92E0108DF928FB39CCB /* Switch.swift in Sources */, + C5099A3F4D955165F503506F2D10065D /* SynchronizedDisposeType.swift in Sources */, + 717576C9ABD8ABE8163D441ABE1C4A8D /* SynchronizedOnType.swift in Sources */, + 159C262BD23A08981D11D3B94340848B /* SynchronizedSubscribeType.swift in Sources */, + 313FCC5057970674AB6016DEF7A05902 /* SynchronizedUnsubscribeType.swift in Sources */, + 527C7425A5831BFC30CC9EC216506393 /* TailRecursiveSink.swift in Sources */, + 7F82F4EE1BA91C32CE75312176ACD4F0 /* Take.swift in Sources */, + 480B2F9937EF953E12DE12FCB177C32A /* TakeLast.swift in Sources */, + D932A3F3727B26175B547BA865A76B81 /* TakeUntil.swift in Sources */, + 5CF87E88489D3832C46FAFCE191F78F9 /* TakeWhile.swift in Sources */, + 9C3C83B09DE882AA526C40FDA31B69C8 /* Throttle.swift in Sources */, + 7574EBA19BA114D77C76D2CC1B58E73C /* Timeout.swift in Sources */, + C6EFFFF6D9947B99945FE08559733EF6 /* Timer.swift in Sources */, + 82DB09296E2BC713C6D363528657A3FD /* ToArray.swift in Sources */, + D5ECB1C860D3F53280EE2C5E54D470BD /* Using.swift in Sources */, + 2DF21CC164C25ED6947C67198879DE12 /* Variable.swift in Sources */, + 7E11CAC09AC72BD412078441E2F7BC21 /* VirtualTimeConverterType.swift in Sources */, + FFDD18622776D270EAFE1CF94726C96D /* VirtualTimeScheduler.swift in Sources */, + 84B43422CBE09278E477D1BFF27B07A1 /* Window.swift in Sources */, + 252E1D07E589566E0B8F49C2B9131976 /* WithLatestFrom.swift in Sources */, + BB5C8DC43B5072BBC05F56BF4DFD8CC5 /* Zip+arity.swift in Sources */, + 402BB7DBAC4D93AD381A0075D7BDDDBA /* Zip+CollectionType.swift in Sources */, + B0EAF63B91ABFD39C96353392D157D19 /* Zip.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CABD7A5E996838E97D6AE9D1E4A47DE6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 983C8A7CA7087B8FD905B6392B05B790 /* AlamofireImplementations.swift in Sources */, + 54325B7F87498350C604C429751BEC97 /* APIHelper.swift in Sources */, + 08D2C4B252A264F837733A22CBFB2481 /* APIs.swift in Sources */, + 569684CF06CEDCEA569BEC7910FC6E5B /* Category.swift in Sources */, + 75D86B4420906282E6B3393E98837360 /* Extensions.swift in Sources */, + BB03FC085AE6A19821878DE92116DDD5 /* Models.swift in Sources */, + A1B963DD34D20B255430C99DD78A1D43 /* Order.swift in Sources */, + DA202CAFA730E897B4D302C8C603A7E1 /* Pet.swift in Sources */, + AFF9AA31B242BF7F011D018D1B2A12FC /* PetAPI.swift in Sources */, + 4E1394BCD39E2E3470805196E884B68B /* PetstoreClient-dummy.m in Sources */, + 8634F37209E5506667C604C1973F630D /* StoreAPI.swift in Sources */, + 4B059D5D108F9D2A4E51A6D1B477A2F5 /* Tag.swift in Sources */, + 0A9698AC9DD60FC3721809C6AB9BCE81 /* User.swift in Sources */, + 97AB8959ABA0C9B8D4F400FD814BBB65 /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EDDE9277BF55CC0EE317B81A0DB026A1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8B68A752ED9CC80E5478E4FEC5A5F721 /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 31D9C92344926342E3D2800111C05269 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PetstoreClient; + target = B3F4219972B712BDBD25392781A43848 /* PetstoreClient */; + targetProxy = D6508A8A1DB5D04976ECA9641101DB50 /* PBXContainerItemProxy */; + }; + 57DC5B1E798B66E24E2BEC74CDB6BDF2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */; + targetProxy = 1E7EDC9660FD64A123EAC6BDA4C055AC /* PBXContainerItemProxy */; + }; + 9351A33C64C743193D9663213D4582BD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; + targetProxy = 1B1D2D2B5F790067C63584DC46E8DEED /* PBXContainerItemProxy */; + }; + C9B7EA4A29DBD0225CC347E19EBAC59F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; + targetProxy = 80996B8BB3446668F158E7817336A6E4 /* PBXContainerItemProxy */; + }; + F461599241C7FC6B0184BF7BAAEF658C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */; + targetProxy = C11AB97FC44865EAFD37FD7629B96B72 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 00BCE7A03AB3EB1357203501EA6FCC84 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0166A36C1ECFD7F42214A2DFF894A89E /* RxSwift.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 2B14898A0D927578A91AF17061B0704F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E6403ECBAB24559C81D937984B72A3A7 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3FA451D268613890FA8A5A03801E11D5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 5E62115DE8C09934BF8D2FE5D15FED1E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + ONLY_ACTIVE_ARCH = YES; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E6403ECBAB24559C81D937984B72A3A7 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 8710426EC015A0183026219312A2B17E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 99EA0FE8990CDA4F2B5110D22698851E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9B259A01C5DDE12EA25530F7D005A3D2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + AD723F120D0CDC6265BA516FE35A9BEB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + B0B4110B60B5F7F6D72CFA5E690CEF32 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0166A36C1ECFD7F42214A2DFF894A89E /* RxSwift.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F0817112233556AF9CA538F326C20567 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9B259A01C5DDE12EA25530F7D005A3D2 /* Debug */, + 99EA0FE8990CDA4F2B5110D22698851E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5E62115DE8C09934BF8D2FE5D15FED1E /* Debug */, + 3FA451D268613890FA8A5A03801E11D5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7335F4AA774EFBDED5B7673EF35FCF11 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 00BCE7A03AB3EB1357203501EA6FCC84 /* Debug */, + B0B4110B60B5F7F6D72CFA5E690CEF32 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C17E886D20DFCEDEFC84423D6652F7EE /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AD723F120D0CDC6265BA516FE35A9BEB /* Debug */, + 2B14898A0D927578A91AF17061B0704F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F609276975EA85CEC0F2AA47BE77CDBD /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F0817112233556AF9CA538F326C20567 /* Debug */, + 8710426EC015A0183026219312A2B17E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md new file mode 100644 index 00000000000..d6765d9c9b9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md new file mode 100644 index 00000000000..c024273281e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md @@ -0,0 +1,180 @@ +Miss Electric Eel 2016 RxSwift: ReactiveX for Swift +====================================== + +[![Travis CI](https://travis-ci.org/ReactiveX/RxSwift.svg?branch=master)](https://travis-ci.org/ReactiveX/RxSwift) ![platforms](https://img.shields.io/badge/platforms-iOS%20%7C%20OSX%20%7C%20tvOS%20%7C%20watchOS%20%7C%20Linux%28experimental%29-333333.svg) ![pod](https://img.shields.io/cocoapods/v/RxSwift.svg) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +Xcode 7.3 Swift 2.2 required + +## About Rx + +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface. + +This is a Swift version of [Rx](https://github.com/Reactive-Extensions/Rx.NET). + +It tries to port as many concepts from the original version as possible, but some concepts were adapted for more pleasant and performant integration with iOS/OSX environment. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like the original Rx, its intention is to enable easy composition of asynchronous operations and event/data streams. + +KVO observing, async operations and streams are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [units](Documentation/Units.md) - what is `Driver`, `ControlProperty`, and `Variable` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) +* [what does the the public API look like?](Documentation/API.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](Documentation/Installation.md) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
    [![Slack channel](http://slack.rxswift.org/badge.svg)](http://slack.rxswift.org) [Join Slack Channel](http://slack.rxswift.org/) +* Report a problem using the library. [Open an Issue With Bug Template](ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) + + +###### ... compare + +* [with other libraries](Documentation/ComparisonWithOtherLibraries.md). + + +###### ... find compatible + +* libraries from [RxSwiftCommunity](https://github.com/RxSwiftCommunity). +* [Pods using RxSwift](https://cocoapods.org/?q=uses%3Arxswift). + +###### ... see the broader vision + +* Does this exist for Android? [RxJava](https://github.com/ReactiveX/RxJava) +* Where is all of this going, what is the future, what about reactive architectures, how do you design entire apps this way? [Cycle.js](https://github.com/cyclejs/cycle-core) - this is javascript, but [RxJS](https://github.com/Reactive-Extensions/RxJS) is javascript version of Rx. + +## Usage + + + + + + + + + + + + + + + + + + + +
    Here's an exampleIn Action
    Define search for GitHub repositories ...
    +let searchResults = searchBar.rx_text
    +    .throttle(0.3, scheduler: MainScheduler.instance)
    +    .distinctUntilChanged()
    +    .flatMapLatest { query -> Observable<[Repository]> in
    +        if query.isEmpty {
    +            return Observable.just([])
    +        }
    +
    +        return searchGitHub(query)
    +            .catchErrorJustReturn([])
    +    }
    +    .observeOn(MainScheduler.instance)
    ... then bind the results to your tableview
    +searchResults
    +    .bindTo(tableView.rx_itemsWithCellIdentifier("Cell")) {
    +        (index, repository: Repository, cell) in
    +        cell.textLabel?.text = repository.name
    +        cell.detailTextLabel?.text = repository.url
    +    }
    +    .addDisposableTo(disposeBag)
    + + +## Installation + +Rx doesn't contain any external dependencies. + +These are currently the supported options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +**:warning: IMPORTANT! For tvOS support, CocoaPods `0.39` is required. :warning:** + +``` +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '~> 2.0' + pod 'RxCocoa', '~> 2.0' +end + +# RxTests and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '~> 2.0' + pod 'RxTests', '~> 2.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +``` +$ pod install +``` + +### [Carthage](https://github.com/Carthage/Carthage) + +**Xcode 7.1 required** + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" ~> 2.0 +``` + +``` +$ carthage update +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +``` +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift-[Platform]` and `RxCocoa-[Platform]` targets + + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [Erik Meijer (Wikipedia)](http://en.wikipedia.org/wiki/Erik_Meijer_%28computer_scientist%29) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://www.youtube.com/watch?v=dwP1TNXE6fc) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 00000000000..530142e4e68 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,75 @@ +// +// AnyObserver.swift +// Rx +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +A type-erased `ObserverType`. + +Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +*/ +public struct AnyObserver : ObserverType { + /** + The type of elements in sequence that observer can observe. + */ + public typealias E = Element + + /** + Anonymous event handler type. + */ + public typealias EventHandler = (Event) -> Void + + public let observer: EventHandler + + /** + Construct an instance whose `on(event)` calls `eventHandler(event)` + + - parameter eventHandler: Event handler that observes sequences events. + */ + public init(eventHandler: EventHandler) { + self.observer = eventHandler + } + + /** + Construct an instance whose `on(event)` calls `observer.on(event)` + + - parameter observer: Observer that receives sequence events. + */ + public init(_ observer: O) { + self.observer = observer.on + } + + /** + Send `event` to this observer. + + - parameter event: Event instance. + */ + public func on(event: Event) { + return self.observer(event) + } + + /** + Erases type of observer and returns canonical observer. + + - returns: type erased observer. + */ + public func asObserver() -> AnyObserver { + return self + } +} + +extension ObserverType { + /** + Erases type of observer and returns canonical observer. + + - returns: type erased observer. + */ + public func asObserver() -> AnyObserver { + return AnyObserver(self) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 00000000000..1a6c5911d0b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,19 @@ +// +// Cancelable.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents disposable resource with state tracking. +*/ +public protocol Cancelable : Disposable { + /** + - returns: Was resource disposed. + */ + var disposed: Bool { get } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 00000000000..0d1ab168c24 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,104 @@ +// +// AsyncLock.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + var _lock = SpinLock() + + private var _queue: Queue = Queue(capacity: 0) + + private var _isExecuting: Bool = false + private var _hasFaulted: Bool = false + + // lock { + func lock() { + _lock.lock() + } + + func unlock() { + _lock.unlock() + } + // } + + private func enqueue(action: I) -> I? { + _lock.lock(); defer { _lock.unlock() } // { + if _hasFaulted { + return nil + } + + if _isExecuting { + _queue.enqueue(action) + return nil + } + + _isExecuting = true + + return action + // } + } + + private func dequeue() -> I? { + _lock.lock(); defer { _lock.unlock() } // { + if _queue.count > 0 { + return _queue.dequeue() + } + else { + _isExecuting = false + return nil + } + // } + } + + func invoke(action: I) { + let firstEnqueuedAction = enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + synchronizedDispose() + } + + func _synchronized_dispose() { + _queue = Queue(capacity: 0) + _hasFaulted = true + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 00000000000..d1632f1cebf --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,107 @@ +// +// Lock.swift +// Rx +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol Lock { + func lock() + func unlock() +} + +#if os(Linux) + import Glibc + + /** + Simple wrapper for spin lock. + */ + class SpinLock { + private var _lock: pthread_spinlock_t = 0 + + init() { + if (pthread_spin_init(&_lock, 0) != 0) { + fatalError("Spin lock initialization failed") + } + } + + func lock() { + pthread_spin_lock(&_lock) + } + + func unlock() { + pthread_spin_unlock(&_lock) + } + + func performLocked(@noescape action: () -> Void) { + lock(); defer { unlock() } + action() + } + + func calculateLocked(@noescape action: () -> T) -> T { + lock(); defer { unlock() } + return action() + } + + func calculateLockedOrFail(@noescape action: () throws -> T) throws -> T { + lock(); defer { unlock() } + let result = try action() + return result + } + + deinit { + pthread_spin_destroy(&_lock) + } + } +#else + + // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html + typealias SpinLock = NSRecursiveLock +#endif + +extension NSRecursiveLock : Lock { + func performLocked(@noescape action: () -> Void) { + lock(); defer { unlock() } + action() + } + + func calculateLocked(@noescape action: () -> T) -> T { + lock(); defer { unlock() } + return action() + } + + func calculateLockedOrFail(@noescape action: () throws -> T) throws -> T { + lock(); defer { unlock() } + let result = try action() + return result + } +} + +/* +let RECURSIVE_MUTEX = _initializeRecursiveMutex() + +func _initializeRecursiveMutex() -> pthread_mutex_t { + var mutex: pthread_mutex_t = pthread_mutex_t() + var mta: pthread_mutexattr_t = pthread_mutexattr_t() + + pthread_mutex_init(&mutex, nil) + pthread_mutexattr_init(&mta) + pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE) + pthread_mutex_init(&mutex, &mta) + + return mutex +} + +extension pthread_mutex_t { + mutating func lock() { + pthread_mutex_lock(&self) + } + + mutating func unlock() { + pthread_mutex_unlock(&self) + } +} +*/ diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 00000000000..b11fcaa87df --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,23 @@ +// +// LockOwnerType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol LockOwnerType : class, Lock { + var _lock: NSRecursiveLock { get } +} + +extension LockOwnerType { + func lock() { + _lock.lock() + } + + func unlock() { + _lock.unlock() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 00000000000..5764575e899 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,20 @@ +// +// SynchronizedDisposeType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedDisposeType : class, Disposable, Lock { + func _synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + lock(); defer { unlock() } + _synchronized_dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 00000000000..84a3df5d104 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,20 @@ +// +// SynchronizedOnType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedOnType : class, ObserverType, Lock { + func _synchronized_on(event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(event: Event) { + lock(); defer { unlock() } + _synchronized_on(event) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift new file mode 100644 index 00000000000..a4903157511 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift @@ -0,0 +1,20 @@ +// +// SynchronizedSubscribeType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedSubscribeType : class, ObservableType, Lock { + func _synchronized_subscribe(observer: O) -> Disposable +} + +extension SynchronizedSubscribeType { + func synchronizedSubscribe(observer: O) -> Disposable { + lock(); defer { unlock() } + return _synchronized_subscribe(observer) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 00000000000..4f41cb89a66 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,15 @@ +// +// SynchronizedUnsubscribeType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedUnsubscribeType : class { + associatedtype DisposeKey + + func synchronizedUnsubscribe(disposeKey: DisposeKey) +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 00000000000..2ba55dc60f7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,21 @@ +// +// ConnectableObservableType.swift +// Rx +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift new file mode 100644 index 00000000000..f886f249f36 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift @@ -0,0 +1,328 @@ +// +// Bag.swift +// Rx +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import Swift + +let arrayDictionaryMaxSize = 30 + +/** +Class that enables using memory allocations as a means to uniquely identify objects. +*/ +class Identity { + // weird things have known to happen with Swift + var _forceAllocation: Int32 = 0 +} + +func hash(_x: Int) -> Int { + var x = _x + x = ((x >> 16) ^ x) &* 0x45d9f3b + x = ((x >> 16) ^ x) &* 0x45d9f3b + x = ((x >> 16) ^ x) + return x; +} + +/** +Unique identifier for object added to `Bag`. +*/ +public struct BagKey : Hashable { + let uniqueIdentity: Identity? + let key: Int + + public var hashValue: Int { + if let uniqueIdentity = uniqueIdentity { + return hash(key) ^ (unsafeAddressOf(uniqueIdentity).hashValue) + } + else { + return hash(key) + } + } +} + +/** +Compares two `BagKey`s. +*/ +public func == (lhs: BagKey, rhs: BagKey) -> Bool { + return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion an deletion is O(n). + +It is suitable for storing small number of elements. +*/ +public struct Bag : CustomDebugStringConvertible { + /** + Type of identifier for inserted elements. + */ + public typealias KeyType = BagKey + + private typealias ScopeUniqueTokenType = Int + + typealias Entry = (key: BagKey, value: T) + + private var _uniqueIdentity: Identity? + private var _nextKey: ScopeUniqueTokenType = 0 + + // data + + // first fill inline variables + private var _key0: BagKey? = nil + private var _value0: T? = nil + + private var _key1: BagKey? = nil + private var _value1: T? = nil + + // then fill "array dictionary" + private var _pairs = ContiguousArray() + + // last is sparse dictionary + private var _dictionary: [BagKey : T]? = nil + + private var _onlyFastPath = true + + /** + Creates new empty `Bag`. + */ + public init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + public mutating func insert(element: T) -> BagKey { + _nextKey = _nextKey &+ 1 + +#if DEBUG + _nextKey = _nextKey % 20 +#endif + + if _nextKey == 0 { + _uniqueIdentity = Identity() + } + + let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _key1 == nil { + _key1 = key + _value1 = element + return key + } + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append(key: key, value: element) + return key + } + + if _dictionary == nil { + _dictionary = [:] + } + + _dictionary![key] = element + + return key + } + + /** + - returns: Number of elements in bag. + */ + public var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount + } + + /** + Removes all elements from bag and clears capacity. + */ + public mutating func removeAll() { + _key0 = nil + _value0 = nil + _key1 = nil + _value1 = nil + + _pairs.removeAll(keepCapacity: false) + _dictionary?.removeAll(keepCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + public mutating func removeKey(key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if _key1 == key { + _key1 = nil + let value = _value1! + _value1 = nil + return value + } + + if let existingObject = _dictionary?.removeValueForKey(key) { + return existingObject + } + + for i in 0 ..< _pairs.count { + if _pairs[i].key == key { + let value = _pairs[i].value + _pairs.removeAtIndex(i) + return value + } + } + + return nil + } +} + +extension Bag { + /** + A textual representation of `self`, suitable for debugging. + */ + public var debugDescription : String { + return "\(self.count) elements in Bag" + } +} + + +// MARK: forEach + +extension Bag { + /** + Enumerates elements inside the bag. + + - parameter action: Enumeration closure. + */ + public func forEach(@noescape action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let pairs = _pairs + let value0 = _value0 + let value1 = _value1 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + if let value1 = value1 { + action(value1) + } + + for i in 0 ..< pairs.count { + action(pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension Bag where T: ObserverType { + /** + Dispatches `event` to app observers contained inside bag. + + - parameter action: Enumeration closure. + */ + public func on(event: Event) { + if _onlyFastPath { + _value0?.on(event) + return + } + + let pairs = _pairs + let value0 = _value0 + let value1 = _value1 + let dictionary = _dictionary + + if let value0 = value0 { + value0.on(event) + } + + if let value1 = value1 { + value1.on(event) + } + + for i in 0 ..< pairs.count { + pairs[i].value.on(event) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + element.on(event) + } + } + } +} + +/** +Dispatches `dispose` to all disposables contained inside bag. +*/ +public func disposeAllIn(bag: Bag) { + if bag._onlyFastPath { + bag._value0?.dispose() + return + } + + let pairs = bag._pairs + let value0 = bag._value0 + let value1 = bag._value1 + let dictionary = bag._dictionary + + if let value0 = value0 { + value0.dispose() + } + + if let value1 = value1 { + value1.dispose() + } + + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + element.dispose() + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift new file mode 100644 index 00000000000..33ead5ec09f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift @@ -0,0 +1,30 @@ +// +// InfiniteSequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Sequence that repeats `repeatedValue` infinite number of times. +*/ +struct InfiniteSequence : SequenceType { + typealias Element = E + typealias Generator = AnyGenerator + + private let _repeatedValue: E + + init(repeatedValue: E) { + _repeatedValue = repeatedValue + } + + func generate() -> Generator { + let repeatedValue = _repeatedValue + return AnyGenerator { + return repeatedValue + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift new file mode 100644 index 00000000000..efbd546a453 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift @@ -0,0 +1,120 @@ +// +// PriorityQueue.swift +// Rx +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct PriorityQueue { + private let _hasHigherPriority: (Element, Element) -> Bool + private var _elements = [Element]() + + init(hasHigherPriority: (Element, Element) -> Bool) { + _hasHigherPriority = hasHigherPriority + } + + mutating func enqueue(element: Element) { + _elements.append(element) + bubbleToHigherPriority(_elements.count - 1) + } + + func peek() -> Element? { + return _elements.first + } + + var isEmpty: Bool { + return _elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(element: Element) { + for i in 0 ..< _elements.count { + if _elements[i] === element { + removeAt(i) + return + } + } + } + + private mutating func removeAt(index: Int) { + let removingLast = index == _elements.count - 1 + if !removingLast { + swap(&_elements[index], &_elements[_elements.count - 1]) + } + + _elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + + if _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) { + swap(&_elements[unbalancedIndex], &_elements[parentIndex]) + + unbalancedIndex = parentIndex + } + else { + break + } + } + } + + private mutating func bubbleToLowerPriority(initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + repeat { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + if highestPriorityIndex != unbalancedIndex { + swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex]) + + unbalancedIndex = highestPriorityIndex + } + else { + break + } + } while true + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + return _elements.debugDescription + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift new file mode 100644 index 00000000000..4bf95889861 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift @@ -0,0 +1,168 @@ +// +// Queue.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +public struct Queue: SequenceType { + /** + Type of generator. + */ + public typealias Generator = AnyGenerator + + private let _resizeFactor = 2 + + private var _storage: ContiguousArray + private var _count = 0 + private var _pushNextIndex = 0 + private var _initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + public init(capacity: Int) { + _initialCapacity = capacity + + _storage = ContiguousArray(count: capacity, repeatedValue: nil) + } + + private var dequeueIndex: Int { + let index = _pushNextIndex - count + return index < 0 ? index + _storage.count : index + } + + /** + - returns: Is queue empty. + */ + public var isEmpty: Bool { + return count == 0 + } + + /** + - returns: Number of elements inside queue. + */ + public var count: Int { + return _count + } + + /** + - returns: Element in front of a list of elements to `dequeue`. + */ + public func peek() -> T { + precondition(count > 0) + + return _storage[dequeueIndex]! + } + + mutating private func resizeTo(size: Int) { + var newStorage = ContiguousArray(count: size, repeatedValue: nil) + + let count = _count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = _storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch] + + _count = count + _pushNextIndex = count + _storage = newStorage + } + + /** + Enqueues `element`. + + - parameter element: Element to enqueue. + */ + public mutating func enqueue(element: T) { + if count == _storage.count { + resizeTo(max(_storage.count, 1) * _resizeFactor) + } + + _storage[_pushNextIndex] = element + _pushNextIndex += 1 + _count += 1 + + if _pushNextIndex >= _storage.count { + _pushNextIndex -= _storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + _storage[index] = nil + _count -= 1 + } + + return _storage[index]! + } + + /** + Dequeues element or throws an exception in case queue is empty. + + - returns: Dequeued element. + */ + public mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor) + if _count < downsizeLimit && downsizeLimit >= _initialCapacity { + resizeTo(_storage.count / _resizeFactor) + } + } + + return dequeueElementOnly() + } + + /** + - returns: Generator of contained elements. + */ + public func generate() -> Generator { + var i = dequeueIndex + var count = _count + + return AnyGenerator { + if count == 0 { + return nil + } + + defer { + count -= 1 + i += 1 + } + + if i >= self._storage.count { + i -= self._storage.count + } + + return self._storage[i] + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 00000000000..da760fff763 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,15 @@ +// +// Disposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Respresents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 00000000000..17a40910be0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,54 @@ +// +// AnonymousDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an Action-based disposable. + +When dispose method is called, disposal action will be dereferenced. +*/ +public final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private var _disposed: AtomicInt = 0 + private var _disposeAction: DisposeAction? + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed == 1 + } + + /** + Constructs a new disposable with the given action used for disposal. + + - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + */ + public init(_ disposeAction: DisposeAction) { + _disposeAction = disposeAction + super.init() + } + + /** + Calls the disposal action if and only if the current instance hasn't been disposed yet. + + After invoking disposal action, disposal action will be dereferenced. + */ + public func dispose() { + if AtomicCompareAndSwap(0, 1, &_disposed) { + assert(_disposed == 1) + + if let action = _disposeAction { + _disposeAction = nil + action() + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 00000000000..b6176592fdc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,54 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents two disposable resources that are disposed together. +*/ +public final class BinaryDisposable : DisposeBase, Cancelable { + + private var _disposed: AtomicInt = 0 + + // state + private var _disposable1: Disposable? + private var _disposable2: Disposable? + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed > 0 + } + + /** + Constructs new binary disposable from two disposables. + + - parameter disposable1: First disposable + - parameter disposable2: Second disposable + */ + init(_ disposable1: Disposable, _ disposable2: Disposable) { + _disposable1 = disposable1 + _disposable2 = disposable2 + super.init() + } + + /** + Calls the disposal action if and only if the current instance hasn't been disposed yet. + + After invoking disposal action, disposal action will be dereferenced. + */ + public func dispose() { + if AtomicCompareAndSwap(0, 1, &_disposed) { + _disposable1?.dispose() + _disposable2?.dispose() + _disposable1 = nil + _disposable2 = nil + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 00000000000..28db627b14a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,45 @@ +// +// BooleanDisposable.swift +// Rx +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable resource that can be checked for disposal status. +*/ +public class BooleanDisposable : Disposable, Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(disposed: true) + private var _disposed = false + + /** + Initializes a new instance of the `BooleanDisposable` class + */ + public init() { + } + + /** + Initializes a new instance of the `BooleanDisposable` class with given value + */ + public init(disposed: Bool) { + self._disposed = disposed + } + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed + } + + /** + Sets the status to disposed, which can be observer through the `disposed` property. + */ + public func dispose() { + _disposed = true + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 00000000000..a787f3625fd --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,135 @@ +// +// CompositeDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a group of disposable resources that are disposed together. +*/ +public class CompositeDisposable : DisposeBase, Disposable, Cancelable { + public typealias DisposeKey = Bag.KeyType + + private var _lock = SpinLock() + + // state + private var _disposables: Bag? = Bag() + + public var disposed: Bool { + _lock.lock(); defer { _lock.unlock() } + return _disposables == nil + } + + public override init() { + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _disposables!.insert(disposable1) + _disposables!.insert(disposable2) + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _disposables!.insert(disposable1) + _disposables!.insert(disposable2) + _disposables!.insert(disposable3) + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _disposables!.insert(disposable1) + _disposables!.insert(disposable2) + _disposables!.insert(disposable3) + _disposables!.insert(disposable4) + + for disposable in disposables { + _disposables!.insert(disposable) + } + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(disposables: [Disposable]) { + for disposable in disposables { + _disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func addDisposable(disposable: Disposable) -> DisposeKey? { + let key = _addDisposable(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _addDisposable(disposable: Disposable) -> DisposeKey? { + _lock.lock(); defer { _lock.unlock() } + + return _disposables?.insert(disposable) + } + + /** + - returns: Gets the number of disposables contained in the `CompositeDisposable`. + */ + public var count: Int { + _lock.lock(); defer { _lock.unlock() } + return _disposables?.count ?? 0 + } + + /** + Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + + - parameter disposeKey: Key used to identify disposable to be removed. + */ + public func removeDisposable(disposeKey: DisposeKey) { + _removeDisposable(disposeKey)?.dispose() + } + + private func _removeDisposable(disposeKey: DisposeKey) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + return _disposables?.removeKey(disposeKey) + } + + /** + Disposes all disposables in the group and removes them from the group. + */ + public func dispose() { + if let disposables = _dispose() { + disposeAllIn(disposables) + } + } + + private func _dispose() -> Bag? { + _lock.lock(); defer { _lock.unlock() } + + let disposeBag = _disposables + _disposables = nil + + return disposeBag + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 00000000000..ce1f0b7fce7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,94 @@ +// +// DisposeBag.swift +// Rx +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Disposable { + /** + Adds `self` to `bag`. + + - parameter bag: `DisposeBag` to add `self` to. + */ + public func addDisposableTo(bag: DisposeBag) { + bag.addDisposable(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public class DisposeBag: DisposeBase { + + private var _lock = SpinLock() + + // state + private var _disposables = [Disposable]() + private var _disposed = false + + /** + Constructs new empty dispose bag. + */ + public override init() { + super.init() + } + + /** + Adds `disposable` to be disposed when dispose bag is being deinited. + + - parameter disposable: Disposable to add. + */ + public func addDisposable(disposable: Disposable) { + _addDisposable(disposable)?.dispose() + } + + private func _addDisposable(disposable: Disposable) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _disposed { + return disposable + } + + _disposables.append(disposable) + + return nil + } + + /** + This is internal on purpose, take a look at `CompositeDisposable` instead. + */ + private func dispose() { + let oldDisposables = _dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + _lock.lock(); defer { _lock.unlock() } + + let disposables = _disposables + + _disposables.removeAll(keepCapacity: false) + _disposed = true + + return disposables + } + + deinit { + dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 00000000000..86ecf4198f9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,26 @@ +// +// DisposeBase.swift +// Rx +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Base class for all disposables. +*/ +public class DisposeBase { + init() { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift new file mode 100644 index 00000000000..548a1c3a5c2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift @@ -0,0 +1,10 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// NAryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 00000000000..05048bcea92 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,32 @@ +// +// NopDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable that does nothing on disposal. + +Nop = No Operation +*/ +public struct NopDisposable : Disposable { + + /** + Singleton instance of `NopDisposable`. + */ + public static let instance: Disposable = NopDisposable() + + init() { + + } + + /** + Does nothing. + */ + public func dispose() { + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 00000000000..2d29d74a33f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,127 @@ +// +// RefCountDisposable.swift +// Rx +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ +public class RefCountDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + private var _disposable = nil as Disposable? + private var _primaryDisposed = false + private var _count = 0 + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + _lock.lock(); defer { _lock.unlock() } + return _disposable == nil + } + + /** + Initializes a new instance of the `RefCountDisposable`. + */ + public init(disposable: Disposable) { + _disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + return _lock.calculateLocked { + if let _ = _disposable { + + do { + try incrementChecked(&_count) + } catch (_) { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return NopDisposable.instance + } + } + } + + /** + Disposes the underlying disposable only when all dependent disposables have been disposed. + */ + public func dispose() { + let oldDisposable: Disposable? = _lock.calculateLocked { + if let oldDisposable = _disposable where !_primaryDisposed + { + _primaryDisposed = true + + if (_count == 0) + { + _disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + private func release() { + let oldDisposable: Disposable? = _lock.calculateLocked { + if let oldDisposable = _disposable { + do { + try decrementChecked(&_count) + } catch (_) { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard _count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if _primaryDisposed && _count == 0 { + _disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let _parent: RefCountDisposable + private var _disposed: AtomicInt = 0 + + init(_ parent: RefCountDisposable) + { + _parent = parent + super.init() + } + + internal func dispose() + { + if AtomicCompareAndSwap(0, 1, &_disposed) { + _parent.release() + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 00000000000..ac734996c46 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,58 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +private let disposeScheduledDisposable: ScheduledDisposable -> Disposable = { sd in + sd.disposeInner() + return NopDisposable.instance +} + +/** +Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +*/ +public class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private var _disposed: AtomicInt = 0 + + // state + private var _disposable: Disposable? + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed == 1 + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + _disposable = disposable + } + + /** + Disposes the wrapped disposable on the provided scheduler. + */ + public func dispose() { + scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if AtomicCompareAndSwap(0, 1, &_disposed) { + _disposable!.dispose() + _disposable = nil + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 00000000000..07eebcc1cb5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,85 @@ +// +// SerialDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +*/ +public class SerialDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + + // state + private var _current = nil as Disposable? + private var _disposed = false + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed + } + + /** + Initializes a new instance of the `SerialDisposable`. + */ + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + return _lock.calculateLocked { + return self.disposable + } + } + set (newDisposable) { + let disposable: Disposable? = _lock.calculateLocked { + if _disposed { + return newDisposable + } + else { + let toDispose = _current + _current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /** + Disposes the underlying disposable as well as all future replacements. + */ + public func dispose() { + _dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _disposed { + return nil + } + else { + _disposed = true + let current = _current + _current = nil + return current + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 00000000000..2b192bac869 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,89 @@ +// +// SingleAssignmentDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public class SingleAssignmentDisposable : DisposeBase, Disposable, Cancelable { + private var _lock = SpinLock() + + // state + private var _disposed = false + private var _disposableSet = false + private var _disposable = nil as Disposable? + + /** + - returns: A value that indicates whether the object is disposed. + */ + public var disposed: Bool { + return _disposed + } + + /** + Initializes a new instance of the `SingleAssignmentDisposable`. + */ + public override init() { + super.init() + } + + /** + Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + + **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + */ + public var disposable: Disposable { + get { + _lock.lock(); defer { _lock.unlock() } + return _disposable ?? NopDisposable.instance + } + set { + _setDisposable(newValue)?.dispose() + } + } + + private func _setDisposable(newValue: Disposable) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _disposableSet { + rxFatalError("oldState.disposable != nil") + } + + _disposableSet = true + + if _disposed { + return newValue + } + + _disposable = newValue + + return nil + } + + /** + Disposes the underlying disposable. + */ + public func dispose() { + if _disposed { + return + } + _dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + + _disposed = true + let disposable = _disposable + _disposable = nil + + return disposable + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift new file mode 100644 index 00000000000..54162d2ee63 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift @@ -0,0 +1,15 @@ +// +// StableCompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +public final class StableCompositeDisposable { + public static func create(disposable1: Disposable, _ disposable2: Disposable) -> Disposable { + return BinaryDisposable(disposable1, disposable2) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 00000000000..7a3e1e97053 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,23 @@ +// +// SubscriptionDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct SubscriptionDisposable : Disposable { + private let _key: T.DisposeKey + private weak var _owner: T? + + init(owner: T, key: T.DisposeKey) { + _owner = owner + _key = key + } + + func dispose() { + _owner?.synchronizedUnsubscribe(_key) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 00000000000..3ac4ac9e92d --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,72 @@ +// +// Errors.swift +// Rx +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/** +Generic Rx error codes. +*/ +public enum RxError + : ErrorType + , CustomDebugStringConvertible { + /** + Unknown error occurred. + */ + case Unknown + /** + Performing an action on disposed object. + */ + case Disposed(object: AnyObject) + /** + Aritmetic overflow error. + */ + case Overflow + /** + Argument out of range error. + */ + case ArgumentOutOfRange + /** + Sequence doesn't contain any elements. + */ + case NoElements + /** + Sequence contains more than one element. + */ + case MoreThanOneElement + /** + Timeout error. + */ + case Timeout +} + +public extension RxError { + /** + A textual representation of `self`, suitable for debugging. + */ + public var debugDescription: String { + switch self { + case .Unknown: + return "Unknown error occurred." + case .Disposed(let object): + return "Object `\(object)` was already disposed." + case .Overflow: + return "Arithmetic overflow occurred." + case .ArgumentOutOfRange: + return "Argument out of range." + case .NoElements: + return "Sequence doesn't contain any elements." + case .MoreThanOneElement: + return "Sequence contains more than one element." + case .Timeout: + return "Sequence timeout." + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 00000000000..46e5f1b13d8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,66 @@ +// +// Event.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a sequence event. + +Sequence grammar: +Next\* (Error | Completed) +*/ +public enum Event { + /// Next element is produced. + case Next(Element) + + /// Sequence terminated with an error. + case Error(ErrorType) + + /// Sequence completed successfully. + case Completed +} + +extension Event : CustomDebugStringConvertible { + /// - returns: Description of event. + public var debugDescription: String { + switch self { + case .Next(let value): + return "Next(\(value))" + case .Error(let error): + return "Error(\(error))" + case .Completed: + return "Completed" + } + } +} + +extension Event { + /// - returns: Is `Completed` or `Error` event. + public var isStopEvent: Bool { + switch self { + case .Next: return false + case .Error, .Completed: return true + } + } + + /// - returns: If `Next` event, returns element value. + public var element: Element? { + if case .Next(let value) = self { + return value + } + return nil + } + + /// - returns: If `Error` event, returns error. + public var error: ErrorType? { + if case .Error(let error) = self { + return error + } + return nil + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift new file mode 100644 index 00000000000..430fc3a3fec --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift @@ -0,0 +1,26 @@ +// +// String+Rx.swift +// Rx +// +// Created by Krunoslav Zaher on 12/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension String { + /** + This is needed because on Linux Swift doesn't have `rangeOfString(..., options: .BackwardsSearch)` + */ + func lastIndexOf(character: Character) -> Index? { + var index = endIndex + while index > startIndex { + index = index.predecessor() + if self[index] == character { + return index + } + } + + return nil + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 00000000000..c4345e96f50 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,40 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an object that immediately schedules units of work. +*/ +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(state: State, action: (state: State, recurse: (State) -> ()) -> ()) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return AnonymousDisposable(recursiveScheduler.dispose) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift new file mode 100644 index 00000000000..c44b9b05125 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift @@ -0,0 +1,128 @@ +// +// Observable+Extensions.swift +// Rx +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribe(on: (event: Event) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + on(event: e) + } + return self.subscribeSafe(observer) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is cancelled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribe(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) + -> Disposable { + + let disposable: Disposable + + if let disposed = onDisposed { + disposable = AnonymousDisposable(disposed) + } + else { + disposable = NopDisposable.instance + } + + let observer = AnonymousObserver { e in + switch e { + case .Next(let value): + onNext?(value) + case .Error(let e): + onError?(e) + disposable.dispose() + case .Completed: + onCompleted?() + disposable.dispose() + } + } + return BinaryDisposable( + self.subscribeSafe(observer), + disposable + ) + } + + /** + Subscribes an element handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribeNext(onNext: (E) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + if case .Next(let value) = e { + onNext(value) + } + } + return self.subscribeSafe(observer) + } + + /** + Subscribes an error handler to an observable sequence. + + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribeError(onError: (ErrorType) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + if case .Error(let error) = e { + onError(error) + } + } + return self.subscribeSafe(observer) + } + + /** + Subscribes a completion handler to an observable sequence. + + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribeCompleted(onCompleted: () -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + if case .Completed = e { + onCompleted() + } + } + return self.subscribeSafe(observer) + } +} + +public extension ObservableType { + /** + All internal subscribe calls go through this method. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + func subscribeSafe(observer: O) -> Disposable { + return self.asObservable().subscribe(observer) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 00000000000..cc472a0c9b7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,51 @@ +// +// Observable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +A type-erased `ObservableType`. + +It represents a push style sequence. +*/ +public class Observable : ObservableType { + /** + Type of elements in sequence. + */ + public typealias E = Element + + init() { +#if TRACE_RESOURCES + OSAtomicIncrement32(&resourceCount) +#endif + } + + public func subscribe(observer: O) -> Disposable { + abstractMethod() + } + + public func asObservable() -> Observable { + return self + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } + + // this is kind of ugly I know :( + // Swift compiler reports "Not supported yet" when trying to override protocol extensions, so ¯\_(ツ)_/¯ + + /** + Optimizations for map operator + */ + internal func composeMap(selector: Element throws -> R) -> Observable { + return Map(source: self, selector: selector) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 00000000000..802cc472fd4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,26 @@ +// +// ObservableConvertibleType.swift +// Rx +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Type that can be converted to observable sequence (`Observer`). +*/ +public protocol ObservableConvertibleType { + /** + Type of elements in sequence. + */ + associatedtype E + + /** + Converts `self` to `Observable` sequence. + + - returns: Observable sequence that represents `self`. + */ + func asObservable() -> Observable +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 00000000000..4f7037845a5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,57 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a push style sequence. +*/ +public protocol ObservableType : ObservableConvertibleType { + /** + Type of elements in sequence. + */ + associatedtype E + + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediately, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + func subscribe(observer: O) -> Disposable + +} + +extension ObservableType { + + /** + Default implementation of converting `ObservableType` to `Observable`. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func asObservable() -> Observable { + return Observable.create(self.subscribe) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift new file mode 100644 index 00000000000..211a9d41f34 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift @@ -0,0 +1,47 @@ +// +// AddRef.swift +// Rx +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class AddRefSink : Sink, ObserverType { + typealias Element = O.E + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(_): + forwardOn(event) + case .Completed, .Error(_): + forwardOn(event) + dispose() + } + } +} + +class AddRef : Producer { + typealias EventHandler = Event throws -> Void + + private let _source: Observable + private let _refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + _source = source + _refCount = refCount + } + + override func run(observer: O) -> Disposable { + let releaseDisposable = _refCount.retain() + let sink = AddRefSink(observer: observer) + sink.disposable = StableCompositeDisposable.create(releaseDisposable, _source.subscribeSafe(sink)) + + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift new file mode 100644 index 00000000000..7e9b5452294 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift @@ -0,0 +1,122 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +enum AmbState { + case Neither + case Left + case Right +} + +class AmbObserver : ObserverType { + typealias Element = ElementType + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + private let _parent: Parent + private var _sink: Sink + private var _cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: Sink) { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + + _parent = parent + _sink = sink + _cancel = cancel + } + + func on(event: Event) { + _sink(self, event) + if event.isStopEvent { + _cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } +} + +class AmbSink : Sink { + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let _parent: Parent + + private let _lock = NSRecursiveLock() + // state + private var _choice = AmbState.Neither + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = StableCompositeDisposable.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self._lock.performLocked { + if self._choice == .Neither { + self._choice = me + o._sink = forwardEvent + o._cancel = disposeAll + otherSubscription.dispose() + } + + if self._choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .Left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .Right, subscription1) + } + + subscription1.disposable = _parent._left.subscribe(sink1) + subscription2.disposable = _parent._right.subscribe(sink2) + + return disposeAll + } +} + +class Amb: Producer { + private let _left: Observable + private let _right: Observable + + init(left: Observable, right: Observable) { + _left = left + _right = right + } + + override func run(observer: O) -> Disposable { + let sink = AmbSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift new file mode 100644 index 00000000000..11346a9ff66 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift @@ -0,0 +1,56 @@ +// +// AnonymousObservable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class AnonymousObservableSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = AnonymousObservable + + // state + private var _isStopped: AtomicInt = 0 + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next: + if _isStopped == 1 { + return + } + forwardOn(event) + case .Error, .Completed: + if AtomicCompareAndSwap(0, 1, &_isStopped) { + forwardOn(event) + dispose() + } + } + } + + func run(parent: Parent) -> Disposable { + return parent._subscribeHandler(AnyObserver(self)) + } +} + +class AnonymousObservable : Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let _subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: SubscribeHandler) { + _subscribeHandler = subscribeHandler + } + + override func run(observer: O) -> Disposable { + let sink = AnonymousObservableSink(observer: observer) + sink.disposable = sink.run(self) + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift new file mode 100644 index 00000000000..0fa4714f2a3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift @@ -0,0 +1,119 @@ +// +// Buffer.swift +// Rx +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class BufferTimeCount : Producer<[Element]> { + + private let _timeSpan: RxTimeInterval + private let _count: Int + private let _scheduler: SchedulerType + private let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + _source = source + _timeSpan = timeSpan + _count = count + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = BufferTimeCountSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Parent = BufferTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + private let _timerD = SerialDisposable() + private var _buffer = [Element]() + private var _windowID = 0 + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + createTimer(_windowID) + return StableCompositeDisposable.create(_timerD, _parent._source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + _windowID = _windowID &+ 1 + let windowID = _windowID + + let buffer = _buffer + _buffer = [] + forwardOn(.Next(buffer)) + + createTimer(windowID) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _buffer.append(element) + + if _buffer.count == _parent._count { + startNewWindowAndSendCurrentOne() + } + + case .Error(let error): + _buffer = [] + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Next(_buffer)) + forwardOn(.Completed) + dispose() + } + } + + func createTimer(windowID: Int) { + if _timerD.disposed { + return + } + + if _windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + _timerD.disposable = nextTimer + + nextTimer.disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in + self._lock.performLocked { + if previousWindowID != self._windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return NopDisposable.instance + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift new file mode 100644 index 00000000000..5f73d40538f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift @@ -0,0 +1,162 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// catch with callback + +class CatchSinkProxy : ObserverType { + typealias E = O.E + typealias Parent = CatchSink + + private let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + _parent.forwardOn(event) + + switch event { + case .Next: + break + case .Error, .Completed: + _parent.dispose() + } + } +} + +class CatchSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = Catch + + private let _parent: Parent + private let _subscription = SerialDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + _subscription.disposable = d1 + d1.disposable = _parent._source.subscribe(self) + + return _subscription + } + + func on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Completed: + forwardOn(event) + dispose() + case .Error(let error): + do { + let catchSequence = try _parent._handler(error) + + let observer = CatchSinkProxy(parent: self) + + _subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + } + } +} + +class Catch : Producer { + typealias Handler = (ErrorType) throws -> Observable + + private let _source: Observable + private let _handler: Handler + + init(source: Observable, handler: Handler) { + _source = source + _handler = handler + } + + override func run(observer: O) -> Disposable { + let sink = CatchSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +// catch enumerable + +class CatchSequenceSink + : TailRecursiveSink + , ObserverType { + typealias Element = O.E + typealias Parent = CatchSequence + + private var _lastError: ErrorType? + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Error(let error): + _lastError = error + schedule(.MoveNext) + case .Completed: + forwardOn(event) + dispose() + } + } + + override func subscribeToNext(source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func done() { + if let lastError = _lastError { + forwardOn(.Error(lastError)) + } + else { + forwardOn(.Completed) + } + + self.dispose() + } + + override func extract(observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.generate(), nil) + } + else { + return nil + } + } +} + +class CatchSequence : Producer { + typealias Element = S.Generator.Element.E + + let sources: S + + init(sources: S) { + self.sources = sources + } + + override func run(observer: O) -> Disposable { + let sink = CatchSequenceSink(observer: observer) + sink.disposable = sink.run((self.sources.generate(), nil)) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift new file mode 100644 index 00000000000..7164815d7ab --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift @@ -0,0 +1,125 @@ +// +// CombineLatest+CollectionType.swift +// Rx +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class CombineLatestCollectionTypeSink + : Sink { + typealias Parent = CombineLatestCollectionType + typealias SourceElement = C.Generator.Element.E + + let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + var _numberOfValues = 0 + var _values: [SourceElement?] + var _isDone: [Bool] + var _numberOfDone = 0 + var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O) { + _parent = parent + _values = [SourceElement?](count: parent._count, repeatedValue: nil) + _isDone = [Bool](count: parent._count, repeatedValue: false) + _subscriptions = Array() + _subscriptions.reserveCapacity(parent._count) + + for _ in 0 ..< parent._count { + _subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer) + } + + func on(event: Event, atIndex: Int) { + _lock.lock(); defer { _lock.unlock() } // { + switch event { + case .Next(let element): + if _values[atIndex] == nil { + _numberOfValues += 1 + } + + _values[atIndex] = element + + if _numberOfValues < _parent._count { + let numberOfOthersThatAreDone = self._numberOfDone - (_isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self._parent._count - 1 { + forwardOn(.Completed) + dispose() + } + return + } + + do { + let result = try _parent._resultSelector(_values.map { $0! }) + forwardOn(.Next(result)) + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + if _isDone[atIndex] { + return + } + + _isDone[atIndex] = true + _numberOfDone += 1 + + if _numberOfDone == self._parent._count { + forwardOn(.Completed) + dispose() + } + else { + _subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in _parent._sources.startIndex ..< _parent._sources.endIndex { + let index = j + let source = _parent._sources[i].asObservable() + _subscriptions[j].disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + j += 1 + } + + return CompositeDisposable(disposables: _subscriptions.map { $0 }) + } +} + +class CombineLatestCollectionType : Producer { + typealias ResultSelector = [C.Generator.Element.E] throws -> R + + let _sources: C + let _resultSelector: ResultSelector + let _count: Int + + init(sources: C, resultSelector: ResultSelector) { + _sources = sources + _resultSelector = resultSelector + _count = Int(self._sources.count.toIntMax()) + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift new file mode 100644 index 00000000000..5d5ea47aafc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift @@ -0,0 +1,724 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + + +// 2 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, resultSelector: (O1.E, O2.E) throws -> E) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink2_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest2 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 2, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2) + } +} + +class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let _source1: Observable + let _source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink2_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 3 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, resultSelector: (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink3_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest3 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 3, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3) + } +} + +class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink3_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 4 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink4_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest4 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 4, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4) + } +} + +class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink4_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 5 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink5_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest5 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 5, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5) + } +} + +class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink5_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 6 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink6_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest6 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 6, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + subscription6.disposable = _parent._source6.subscribe(observer6) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6) + } +} + +class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink6_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 7 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink7_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest7 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + var _latestElement7: E7! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 7, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: _lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + subscription6.disposable = _parent._source6.subscribe(observer6) + subscription7.disposable = _parent._source7.subscribe(observer7) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7) + } +} + +class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + _source7 = source7 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink7_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 8 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink8_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest8 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + var _latestElement7: E7! = nil + var _latestElement8: E8! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 8, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: _lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: _lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self._latestElement8 = e }, this: subscription8) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + subscription6.disposable = _parent._source6.subscribe(observer6) + subscription7.disposable = _parent._source7.subscribe(observer7) + subscription8.disposable = _parent._source8.subscribe(observer8) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7, _latestElement8) + } +} + +class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + let _source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + _source7 = source7 + _source8 = source8 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink8_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift new file mode 100644 index 00000000000..6662edb8dcc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift @@ -0,0 +1,134 @@ +// +// CombineLatest.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol CombineLatestProtocol : class { + func next(index: Int) + func fail(error: ErrorType) + func done(index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = O.E + + let _lock = NSRecursiveLock() + + private let _arity: Int + private var _numberOfValues = 0 + private var _numberOfDone = 0 + private var _hasValue: [Bool] + private var _isDone: [Bool] + + init(arity: Int, observer: O) { + _arity = arity + _hasValue = [Bool](count: arity, repeatedValue: false) + _isDone = [Bool](count: arity, repeatedValue: false) + + super.init(observer: observer) + } + + func getResult() throws -> Element { + abstractMethod() + } + + func next(index: Int) { + if !_hasValue[index] { + _hasValue[index] = true + _numberOfValues += 1 + } + + if _numberOfValues == _arity { + do { + let result = try getResult() + forwardOn(.Next(result)) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< _arity { + if i != index && !_isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + forwardOn(.Completed) + dispose() + } + } + } + + func fail(error: ErrorType) { + forwardOn(.Error(error)) + dispose() + } + + func done(index: Int) { + if _isDone[index] { + return + } + + _isDone[index] = true + _numberOfDone += 1 + + if _numberOfDone == _arity { + forwardOn(.Completed) + dispose() + } + } +} + +class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = ElementType + typealias ValueSetter = (Element) -> Void + + private let _parent: CombineLatestProtocol + + let _lock: NSRecursiveLock + private let _index: Int + private let _this: Disposable + private let _setLatestValue: ValueSetter + + init(lock: NSRecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: ValueSetter, this: Disposable) { + _lock = lock + _parent = parent + _index = index + _this = this + _setLatestValue = setLatestValue + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let value): + _setLatestValue(value) + _parent.next(_index) + case .Error(let error): + _this.dispose() + _parent.fail(error) + case .Completed: + _this.dispose() + _parent.done(_index) + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift new file mode 100644 index 00000000000..85feff2e871 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift @@ -0,0 +1,63 @@ +// +// Concat.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + +class ConcatSink + : TailRecursiveSink + , ObserverType { + typealias Element = O.E + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event){ + switch event { + case .Next: + forwardOn(event) + case .Error: + forwardOn(event) + dispose() + case .Completed: + schedule(.MoveNext) + } + } + + override func subscribeToNext(source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func extract(observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source._sources.generate(), source._count) + } + else { + return nil + } + } +} + +class Concat : Producer { + typealias Element = S.Generator.Element.E + + private let _sources: S + private let _count: IntMax? + + init(sources: S, count: IntMax?) { + _sources = sources + _count = count + } + + override func run(observer: O) -> Disposable { + let sink = ConcatSink(observer: observer) + sink.disposable = sink.run((_sources.generate(), _count)) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift new file mode 100644 index 00000000000..72d4ed29cc4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift @@ -0,0 +1,96 @@ +// +// ConnectableObservable.swift +// Rx +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + abstractMethod() + } +} + +class Connection : Disposable { + + private var _lock: NSRecursiveLock + // state + private var _parent: ConnectableObservableAdapter? + private var _subscription : Disposable? + + init(parent: ConnectableObservableAdapter, lock: NSRecursiveLock, subscription: Disposable) { + _parent = parent + _subscription = subscription + _lock = lock + } + + func dispose() { + _lock.lock(); defer { _lock.unlock() } // { + guard let parent = _parent else { + return + } + + guard let oldSubscription = _subscription else { + return + } + + _subscription = nil + if parent._connection === self { + parent._connection = nil + } + _parent = nil + + oldSubscription.dispose() + // } + } +} + +class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + private let _subject: S + private let _source: Observable + + private let _lock = NSRecursiveLock() + + // state + private var _connection: ConnectionType? + + init(source: Observable, subject: S) { + _source = source + _subject = subject + _connection = nil + } + + override func connect() -> Disposable { + return _lock.calculateLocked { + if let connection = _connection { + return connection + } + + let disposable = _source.subscribe(_subject.asObserver()) + let connection = Connection(parent: self, lock: _lock, subscription: disposable) + _connection = connection + return connection + } + } + + override func subscribe(observer: O) -> Disposable { + return _subject.subscribe(observer) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift new file mode 100644 index 00000000000..66b65f25b38 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift @@ -0,0 +1,77 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +func logEvent(identifier: String, dateFormat: NSDateFormatter, content: String) { + print("\(dateFormat.stringFromDate(NSDate())): \(identifier) -> \(content)") +} + +class Debug_ : Sink, ObserverType { + typealias Element = O.E + typealias Parent = Debug + + private let _parent: Parent + private let _timestampFormatter = NSDateFormatter() + + init(parent: Parent, observer: O) { + _parent = parent + _timestampFormatter.dateFormat = dateFormat + + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "subscribed") + + super.init(observer: observer) + } + + func on(event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + let eventNormalized = eventText.characters.count > maxEventTextLength + ? String(eventText.characters.prefix(maxEventTextLength / 2)) + "..." + String(eventText.characters.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)") + forwardOn(event) + } + + override func dispose() { + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "disposed") + super.dispose() + } +} + +class Debug : Producer { + private let _identifier: String + + private let _source: Observable + + init(source: Observable, identifier: String?, file: String, line: UInt, function: String) { + if let identifier = identifier { + _identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndexOf("/") { + trimmedFile = file[lastIndex.successor() ..< file.endIndex] + } + else { + trimmedFile = file + } + _identifier = "\(trimmedFile):\(line) (\(function))" + } + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = Debug_(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift new file mode 100644 index 00000000000..900082c4d93 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift @@ -0,0 +1,61 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DeferredSink : Sink, ObserverType { + typealias E = O.E + + private let _observableFactory: () throws -> S + + init(observableFactory: () throws -> S, observer: O) { + _observableFactory = observableFactory + super.init(observer: observer) + } + + func run() -> Disposable { + do { + let result = try _observableFactory() + return result.subscribe(self) + } + catch let e { + forwardOn(.Error(e)) + dispose() + return NopDisposable.instance + } + } + + func on(event: Event) { + forwardOn(event) + + switch event { + case .Next: + break + case .Error: + dispose() + case .Completed: + dispose() + } + } +} + +class Deferred : Producer { + typealias Factory = () throws -> S + + private let _observableFactory : Factory + + init(observableFactory: Factory) { + _observableFactory = observableFactory + } + + override func run(observer: O) -> Disposable { + let sink = DeferredSink(observableFactory: _observableFactory, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift new file mode 100644 index 00000000000..31d7c7c7a0a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift @@ -0,0 +1,52 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DelaySubscriptionSink + : Sink + , ObserverType { + typealias Parent = DelaySubscription + typealias E = O.E + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + +} + +class DelaySubscription: Producer { + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = DelaySubscriptionSink(parent: self, observer: observer) + sink.disposable = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in + return self._source.subscribe(sink) + } + + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift new file mode 100644 index 00000000000..cff09a898e8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift @@ -0,0 +1,70 @@ +// +// DistinctUntilChanged.swift +// Rx +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DistinctUntilChangedSink: Sink, ObserverType { + typealias E = O.E + + private let _parent: DistinctUntilChanged + private var _currentKey: Key? = nil + + init(parent: DistinctUntilChanged, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + let key = try _parent._selector(value) + var areEqual = false + if let currentKey = _currentKey { + areEqual = try _parent._comparer(currentKey, key) + } + + if areEqual { + return + } + + _currentKey = key + + forwardOn(event) + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + private let _source: Observable + private let _selector: KeySelector + private let _comparer: EqualityComparer + + init(source: Observable, selector: KeySelector, comparer: EqualityComparer) { + _source = source + _selector = selector + _comparer = comparer + } + + override func run(observer: O) -> Disposable { + let sink = DistinctUntilChangedSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift new file mode 100644 index 00000000000..7fc07dcb706 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift @@ -0,0 +1,53 @@ +// +// Do.swift +// Rx +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DoSink : Sink, ObserverType { + typealias Element = O.E + typealias Parent = Do + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + do { + try _parent._eventHandler(event) + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + } +} + +class Do : Producer { + typealias EventHandler = Event throws -> Void + + private let _source: Observable + private let _eventHandler: EventHandler + + init(source: Observable, eventHandler: EventHandler) { + _source = source + _eventHandler = eventHandler + } + + override func run(observer: O) -> Disposable { + let sink = DoSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift new file mode 100644 index 00000000000..158e471572d --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift @@ -0,0 +1,79 @@ +// +// ElementAt.swift +// Rx +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + +class ElementAtSink : Sink, ObserverType { + typealias Parent = ElementAt + + let _parent: Parent + var _i: Int + + init(parent: Parent, observer: O) { + _parent = parent + _i = parent._index + + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(_): + + if (_i == 0) { + forwardOn(event) + forwardOn(.Completed) + self.dispose() + } + + do { + try decrementChecked(&_i) + } catch(let e) { + forwardOn(.Error(e)) + dispose() + return + } + + case .Error(let e): + forwardOn(.Error(e)) + self.dispose() + case .Completed: + if (_parent._throwOnEmpty) { + forwardOn(.Error(RxError.ArgumentOutOfRange)) + } else { + forwardOn(.Completed) + } + + self.dispose() + } + } +} + +class ElementAt : Producer { + + let _source: Observable + let _throwOnEmpty: Bool + let _index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self._source = source + self._index = index + self._throwOnEmpty = throwOnEmpty + } + + override func run(observer: O) -> Disposable { + let sink = ElementAtSink(parent: self, observer: observer) + sink.disposable = _source.subscribeSafe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift new file mode 100644 index 00000000000..d2ebb1886a6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift @@ -0,0 +1,16 @@ +// +// Empty.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Empty : Producer { + override func subscribe(observer: O) -> Disposable { + observer.on(.Completed) + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift new file mode 100644 index 00000000000..ba0abf940a3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift @@ -0,0 +1,22 @@ +// +// Error.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Error : Producer { + private let _error: ErrorType + + init(error: ErrorType) { + _error = error + } + + override func subscribe(observer: O) -> Disposable { + observer.on(.Error(_error)) + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift new file mode 100644 index 00000000000..43d7a18f6c6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift @@ -0,0 +1,60 @@ +// +// Filter.swift +// Rx +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = O.E + + typealias Parent = Filter + + private let _predicate: Predicate + + init(predicate: Predicate, observer: O) { + _predicate = predicate + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + let satisfies = try _predicate(value) + if satisfies { + forwardOn(.Next(value)) + } + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Completed, .Error: + forwardOn(event) + dispose() + } + } +} + +class Filter : Producer { + typealias Predicate = (Element) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate + + init(source: Observable, predicate: Predicate) { + _source = source + _predicate = predicate + } + + override func run(observer: O) -> Disposable { + let sink = FilterSink(predicate: _predicate, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift new file mode 100644 index 00000000000..d60a9b7431c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift @@ -0,0 +1,71 @@ +// +// Generate.swift +// Rx +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class GenerateSink : Sink { + typealias Parent = Generate + + private let _parent: Parent + + private var _state: S + + init(parent: Parent, observer: O) { + _parent = parent + _state = parent._initialState + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in + do { + if !isFirst { + self._state = try self._parent._iterate(self._state) + } + + if try self._parent._condition(self._state) { + let result = try self._parent._resultSelector(self._state) + self.forwardOn(.Next(result)) + + recurse(false) + } + else { + self.forwardOn(.Completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.Error(error)) + self.dispose() + } + } + } +} + +class Generate : Producer { + private let _initialState: S + private let _condition: S throws -> Bool + private let _iterate: S throws -> S + private let _resultSelector: S throws -> E + private let _scheduler: ImmediateSchedulerType + + init(initialState: S, condition: S throws -> Bool, iterate: S throws -> S, resultSelector: S throws -> E, scheduler: ImmediateSchedulerType) { + _initialState = initialState + _condition = condition + _iterate = iterate + _resultSelector = resultSelector + _scheduler = scheduler + super.init() + } + + override func run(observer: O) -> Disposable { + let sink = GenerateSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift new file mode 100644 index 00000000000..d116d641582 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift @@ -0,0 +1,61 @@ +// +// Just.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class JustScheduledSink : Sink { + typealias Parent = JustScheduled + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let scheduler = _parent._scheduler + return scheduler.schedule(_parent._element) { element in + self.forwardOn(.Next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.Completed) + return NopDisposable.instance + } + } + } +} + +class JustScheduled : Producer { + private let _scheduler: ImmediateSchedulerType + private let _element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + _scheduler = scheduler + _element = element + } + + override func subscribe(observer: O) -> Disposable { + let sink = JustScheduledSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +class Just : Producer { + private let _element: Element + + init(element: Element) { + _element = element + } + + override func subscribe(observer: O) -> Disposable { + observer.on(.Next(_element)) + observer.on(.Completed) + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift new file mode 100644 index 00000000000..54a3404dc52 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift @@ -0,0 +1,140 @@ +// +// Map.swift +// Rx +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class MapSink : Sink, ObserverType { + typealias Selector = (SourceType) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let element): + do { + let mappedElement = try _selector(element) + forwardOn(.Next(mappedElement)) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } +} + +class MapWithIndexSink : Sink, ObserverType { + typealias Selector = (SourceType, Int) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + typealias Parent = MapWithIndex + + private let _selector: Selector + + private var _index = 0 + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let element): + do { + let mappedElement = try _selector(element, try incrementChecked(&_index)) + forwardOn(.Next(mappedElement)) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } +} + +class MapWithIndex : Producer { + typealias Selector = (SourceType, Int) throws -> ResultType + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = MapWithIndexSink(selector: _selector, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} + +#if TRACE_RESOURCES +public var numberOfMapOperators: Int32 = 0 +#endif + +class Map: Producer { + typealias Selector = (SourceType) throws -> ResultType + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + +#if TRACE_RESOURCES + AtomicIncrement(&numberOfMapOperators) +#endif + } + + override func composeMap(selector: ResultType throws -> R) -> Observable { + let originalSelector = _selector + return Map(source: _source, selector: { (s: SourceType) throws -> R in + let r: ResultType = try originalSelector(s) + return try selector(r) + }) + } + + override func run(observer: O) -> Disposable { + let sink = MapSink(selector: _selector, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + + #if TRACE_RESOURCES + deinit { + AtomicDecrement(&numberOfMapOperators) + } + #endif +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift new file mode 100644 index 00000000000..0bba8ca7317 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift @@ -0,0 +1,423 @@ +// +// Merge.swift +// Rx +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: Limited concurrency version + +class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = O.E + typealias DisposeKey = Bag.KeyType + typealias Parent = MergeLimitedSink + + private let _parent: Parent + private let _disposeKey: DisposeKey + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + _parent = parent + _disposeKey = disposeKey + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + _parent.forwardOn(event) + case .Error: + _parent.forwardOn(event) + _parent.dispose() + case .Completed: + _parent._group.removeDisposable(_disposeKey) + if let next = _parent._queue.dequeue() { + _parent.subscribe(next, group: _parent._group) + } + else { + _parent._activeCount = _parent._activeCount - 1 + + if _parent._stopped && _parent._activeCount == 0 { + _parent.forwardOn(.Completed) + _parent.dispose() + } + } + } + } +} + +class MergeLimitedSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = S + typealias QueueType = Queue + + private let _maxConcurrent: Int + + let _lock = NSRecursiveLock() + + // state + private var _stopped = false + private var _activeCount = 0 + private var _queue = QueueType(capacity: 2) + + private let _sourceSubscription = SingleAssignmentDisposable() + private let _group = CompositeDisposable() + + init(maxConcurrent: Int, observer: O) { + _maxConcurrent = maxConcurrent + + _group.addDisposable(_sourceSubscription) + super.init(observer: observer) + } + + func run(source: Observable) -> Disposable { + _group.addDisposable(_sourceSubscription) + + let disposable = source.subscribe(self) + _sourceSubscription.disposable = disposable + return _group + } + + func subscribe(innerSource: E, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.addDisposable(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.disposable = disposable + } + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let value): + let subscribe: Bool + if _activeCount < _maxConcurrent { + _activeCount += 1 + subscribe = true + } + else { + _queue.enqueue(value) + subscribe = false + } + + if subscribe { + self.subscribe(value, group: _group) + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + if _activeCount == 0 { + forwardOn(.Completed) + dispose() + } + else { + _sourceSubscription.dispose() + } + + _stopped = true + } + } +} + +class MergeLimited : Producer { + private let _source: Observable + private let _maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + _source = source + _maxConcurrent = maxConcurrent + } + + override func run(observer: O) -> Disposable { + let sink = MergeLimitedSink(maxConcurrent: _maxConcurrent, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +// MARK: Merge + +final class MergeBasicSink : MergeSink { + override init(observer: O) { + super.init(observer: observer) + } + + override func performMap(element: S) throws -> S { + return element + } +} + +// MARK: flatMap + +final class FlatMapSink : MergeSink { + typealias Selector = (SourceType) throws -> S + + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element) + } +} + +final class FlatMapWithIndexSink : MergeSink { + typealias Selector = (SourceType, Int) throws -> S + + private var _index = 0 + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element, try incrementChecked(&_index)) + } +} + +// MARK: FlatMapFirst + +final class FlatMapFirstSink : MergeSink { + typealias Selector = (SourceType) throws -> S + + private let _selector: Selector + + override var subscribeNext: Bool { + return _group.count == MergeNoIterators + } + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element) + } +} + +// It's value is one because initial source subscription is always in CompositeDisposable +private let MergeNoIterators = 1 + +class MergeSinkIter : ObserverType { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias E = O.E + + private let _parent: Parent + private let _disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + _parent = parent + _disposeKey = disposeKey + } + + func on(event: Event) { + switch event { + case .Next(let value): + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + _parent.forwardOn(.Next(value)) + // } + case .Error(let error): + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + _parent.forwardOn(.Error(error)) + _parent.dispose() + // } + case .Completed: + _parent._group.removeDisposable(_disposeKey) + // If this has returned true that means that `Completed` should be sent. + // In case there is a race who will sent first completed, + // lock will sort it out. When first Completed message is sent + // it will set observer to nil, and thus prevent further complete messages + // to be sent, and thus preserving the sequence grammar. + if _parent._stopped && _parent._group.count == MergeNoIterators { + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + _parent.forwardOn(.Completed) + _parent.dispose() + // } + } + } + } +} + + +class MergeSink + : Sink + , ObserverType { + typealias ResultType = O.E + typealias Element = SourceType + + private let _lock = NSRecursiveLock() + + private var subscribeNext: Bool { + return true + } + + // state + private let _group = CompositeDisposable() + private let _sourceSubscription = SingleAssignmentDisposable() + + private var _stopped = false + + override init(observer: O) { + super.init(observer: observer) + } + + func performMap(element: SourceType) throws -> S { + abstractMethod() + } + + func on(event: Event) { + switch event { + case .Next(let element): + if !subscribeNext { + return + } + do { + let value = try performMap(element) + subscribeInner(value.asObservable()) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let error): + _lock.lock(); defer { _lock.unlock() } // lock { + forwardOn(.Error(error)) + dispose() + // } + case .Completed: + _lock.lock(); defer { _lock.unlock() } // lock { + _stopped = true + if _group.count == MergeNoIterators { + forwardOn(.Completed) + dispose() + } + else { + _sourceSubscription.dispose() + } + //} + } + } + + func subscribeInner(source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = _group.addDisposable(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.disposable = subscription + } + } + + func run(source: Observable) -> Disposable { + _group.addDisposable(_sourceSubscription) + + let subscription = source.subscribe(self) + _sourceSubscription.disposable = subscription + + return _group + } +} + +// MARK: Producers + +final class FlatMap: Producer { + typealias Selector = (SourceType) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = FlatMapSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +final class FlatMapWithIndex: Producer { + typealias Selector = (SourceType, Int) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = FlatMapWithIndexSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } + +} + +final class FlatMapFirst: Producer { + typealias Selector = (SourceType) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = FlatMapFirstSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +final class Merge : Producer { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = MergeBasicSink(observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift new file mode 100644 index 00000000000..f91a3a11e1b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift @@ -0,0 +1,71 @@ +// +// Multicast.swift +// Rx +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class MulticastSink: Sink, ObserverType { + typealias Element = O.E + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let _parent: MutlicastType + + init(parent: MutlicastType, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + do { + let subject = try _parent._subjectSelector() + let connectable = ConnectableObservableAdapter(source: _parent._source, subject: subject) + + let observable = try _parent._selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return BinaryDisposable(subscription, connection) + } + catch let e { + forwardOn(.Error(e)) + dispose() + return NopDisposable.instance + } + } + + func on(event: Event) { + forwardOn(event) + switch event { + case .Next: break + case .Error, .Completed: + dispose() + } + } +} + +class Multicast: Producer { + typealias SubjectSelectorType = () throws -> S + typealias SelectorType = (Observable) throws -> Observable + + private let _source: Observable + private let _subjectSelector: SubjectSelectorType + private let _selector: SelectorType + + init(source: Observable, subjectSelector: SubjectSelectorType, selector: SelectorType) { + _source = source + _subjectSelector = subjectSelector + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = MulticastSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift new file mode 100644 index 00000000000..1b20b277877 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift @@ -0,0 +1,15 @@ +// +// Never.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Never : Producer { + override func subscribe(observer: O) -> Disposable { + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift new file mode 100644 index 00000000000..2c458ff405a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift @@ -0,0 +1,133 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ObserveOn : Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + } + + override func run(observer: O) -> Disposable { + let sink = ObserveOnSink(scheduler: scheduler, observer: observer) + sink._subscription.disposable = source.subscribe(sink) + return sink + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case Stopped = 0 + // pump is running + case Running = 1 +} + +class ObserveOnSink : ObserverBase { + typealias E = O.E + + let _scheduler: ImmediateSchedulerType + + var _lock = SpinLock() + + // state + var _state = ObserveOnState.Stopped + var _observer: O? + var _queue = Queue>(capacity: 10) + + let _scheduleDisposable = SerialDisposable() + let _subscription = SingleAssignmentDisposable() + + init(scheduler: ImmediateSchedulerType, observer: O) { + _scheduler = scheduler + _observer = observer + } + + override func onCore(event: Event) { + let shouldStart = _lock.calculateLocked { () -> Bool in + self._queue.enqueue(event) + + switch self._state { + case .Stopped: + self._state = .Running + return true + case .Running: + return false + } + } + + if shouldStart { + _scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(state: Void, recurse: Void -> Void) { + let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event?, O?) in + if self._queue.count > 0 { + return (self._queue.dequeue(), self._observer) + } + else { + self._state = .Stopped + return (nil, self._observer) + } + } + + if let nextEvent = nextEvent { + observer?.on(nextEvent) + if nextEvent.isStopEvent { + dispose() + } + } + else { + return + } + + let shouldContinue = _shouldContinue_synchronized() + + if shouldContinue { + recurse() + } + } + + func _shouldContinue_synchronized() -> Bool { + _lock.lock(); defer { _lock.unlock() } // { + if self._queue.count > 0 { + return true + } + else { + self._state = .Stopped + return false + } + // } + } + + override func dispose() { + super.dispose() + + _subscription.dispose() + _scheduleDisposable.dispose() + + _lock.lock(); defer { _lock.unlock() } // { + _observer = nil + + // } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift new file mode 100644 index 00000000000..714b1304b26 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift @@ -0,0 +1,81 @@ +// +// ObserveOnSerialDispatchQueue.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES +/** +Counts number of `SerialDispatchQueueObservables`. + +Purposed for unit tests. +*/ +public var numberOfSerialDispatchQueueObservables: AtomicInt = 0 +#endif + +class ObserveOnSerialDispatchQueueSink : ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: O + + let subscription = SingleAssignmentDisposable() + + var cachedScheduleLambda: ((ObserveOnSerialDispatchQueueSink, Event) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: O) { + self.scheduler = scheduler + self.observer = observer + super.init() + + cachedScheduleLambda = { sink, event in + sink.observer.on(event) + + if event.isStopEvent { + sink.dispose() + } + + return NopDisposable.instance + } + } + + override func onCore(event: Event) { + self.scheduler.schedule((self, event), action: cachedScheduleLambda) + } + + override func dispose() { + super.dispose() + + subscription.dispose() + } +} + +class ObserveOnSerialDispatchQueue : Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) + AtomicIncrement(&numberOfSerialDispatchQueueObservables) +#endif + } + + override func run(observer: O) -> Disposable { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: scheduler, observer: observer) + sink.subscription.disposable = source.subscribe(sink) + return sink + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + AtomicDecrement(&numberOfSerialDispatchQueueObservables) + } +#endif +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift new file mode 100644 index 00000000000..84048e4bf53 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift @@ -0,0 +1,30 @@ +// +// Producer.swift +// Rx +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Producer : Observable { + override init() { + super.init() + } + + override func subscribe(observer: O) -> Disposable { + if !CurrentThreadScheduler.isScheduleRequired { + return run(observer) + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + return self.run(observer) + } + } + } + + func run(observer: O) -> Disposable { + abstractMethod() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift new file mode 100644 index 00000000000..d01da11a2ea --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift @@ -0,0 +1,59 @@ +// +// Range.swift +// Rx +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RangeProducer : Producer { + private let _start: E + private let _count: E + private let _scheduler: ImmediateSchedulerType + + init(start: E, count: E, scheduler: ImmediateSchedulerType) { + if count < 0 { + rxFatalError("count can't be negative") + } + + if start &+ (count - 1) < start { + rxFatalError("overflow of count") + } + + _start = start + _count = count + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = RangeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +class RangeSink : Sink { + typealias Parent = RangeProducer + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in + if i < self._parent._count { + self.forwardOn(.Next(self._parent._start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.Completed) + self.dispose() + } + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift new file mode 100644 index 00000000000..7709b431a2c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift @@ -0,0 +1,74 @@ +// +// Reduce.swift +// Rx +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ReduceSink : Sink, ObserverType { + typealias ResultType = O.E + typealias Parent = Reduce + + private let _parent: Parent + private var _accumulation: AccumulateType + + init(parent: Parent, observer: O) { + _parent = parent + _accumulation = parent._seed + + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + _accumulation = try _parent._accumulator(_accumulation, value) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let e): + forwardOn(.Error(e)) + dispose() + case .Completed: + do { + let result = try _parent._mapResult(_accumulation) + forwardOn(.Next(result)) + forwardOn(.Completed) + dispose() + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + } + } +} + +class Reduce : Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + private let _source: Observable + private let _seed: AccumulateType + private let _accumulator: AccumulatorType + private let _mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: AccumulatorType, mapResult: ResultSelectorType) { + _source = source + _seed = seed + _accumulator = accumulator + _mapResult = mapResult + } + + override func run(observer: O) -> Disposable { + let sink = ReduceSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift new file mode 100644 index 00000000000..e1450381dc8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift @@ -0,0 +1,84 @@ +// +// RefCount.swift +// Rx +// +// Created by Krunoslav Zaher on 3/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RefCountSink + : Sink + , ObserverType { + typealias Element = O.E + typealias Parent = RefCount + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribeSafe(self) + + _parent._lock.lock(); defer { _parent._lock.unlock() } // { + if _parent._count == 0 { + _parent._count = 1 + _parent._connectableSubscription = _parent._source.connect() + } + else { + _parent._count = _parent._count + 1 + } + // } + + return AnonymousDisposable { + subscription.dispose() + self._parent._lock.lock(); defer { self._parent._lock.unlock() } // { + if self._parent._count == 1 { + self._parent._connectableSubscription!.dispose() + self._parent._count = 0 + self._parent._connectableSubscription = nil + } + else if self._parent._count > 1 { + self._parent._count = self._parent._count - 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + // } + } + } + + func on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class RefCount: Producer { + private let _lock = NSRecursiveLock() + + // state + private var _count = 0 + private var _connectableSubscription = nil as Disposable? + + private let _source: CO + + init(source: CO) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = RefCountSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift new file mode 100644 index 00000000000..0b24510c3ef --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift @@ -0,0 +1,44 @@ +// +// Repeat.swift +// RxExample +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RepeatElement : Producer { + private let _element: Element + private let _scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + _element = element + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = RepeatElementSink(parent: self, observer: observer) + sink.disposable = sink.run() + + return sink + } +} + +class RepeatElementSink : Sink { + typealias Parent = RepeatElement + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(_parent._element) { e, recurse in + self.forwardOn(.Next(e)) + recurse(e) + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift new file mode 100644 index 00000000000..0bbb08cf1c5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift @@ -0,0 +1,150 @@ +// +// RetryWhen.swift +// Rx +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RetryTriggerSink + : ObserverType { + typealias E = TriggerObservable.E + + typealias Parent = RetryWhenSequenceSinkIter + + private let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + switch event { + case .Next: + _parent._parent._lastError = nil + _parent._parent.schedule(.MoveNext) + case .Error(let e): + _parent._parent.forwardOn(.Error(e)) + _parent._parent.dispose() + case .Completed: + _parent._parent.forwardOn(.Completed) + _parent._parent.dispose() + } + } +} + +class RetryWhenSequenceSinkIter + : SingleAssignmentDisposable + , ObserverType { + typealias E = O.E + typealias Parent = RetryWhenSequenceSink + + private let _parent: Parent + private let _errorHandlerSubscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + switch event { + case .Next: + _parent.forwardOn(event) + case .Error(let error): + _parent._lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + super.dispose() + + let errorHandlerSubscription = _parent._notifier.subscribe(RetryTriggerSink(parent: self)) + _errorHandlerSubscription.disposable = errorHandlerSubscription + _parent._errorSubject.on(.Next(failedWith)) + } + else { + _parent.forwardOn(.Error(error)) + _parent.dispose() + } + case .Completed: + _parent.forwardOn(event) + _parent.dispose() + } + } + + override func dispose() { + super.dispose() + _errorHandlerSubscription.dispose() + } +} + +class RetryWhenSequenceSink + : TailRecursiveSink { + typealias Element = O.E + typealias Parent = RetryWhenSequence + + let _lock = NSRecursiveLock() + + private let _parent: Parent + + private var _lastError: ErrorType? + private let _errorSubject = PublishSubject() + private let _handler: Observable + private let _notifier = PublishSubject() + + init(parent: Parent, observer: O) { + _parent = parent + _handler = parent._notificationHandler(_errorSubject).asObservable() + super.init(observer: observer) + } + + override func done() { + if let lastError = _lastError { + forwardOn(.Error(lastError)) + _lastError = nil + } + else { + forwardOn(.Completed) + } + + dispose() + } + + override func extract(observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are sideffects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(source: Observable) -> Disposable { + let iter = RetryWhenSequenceSinkIter(parent: self) + iter.disposable = source.subscribe(iter) + return iter + } + + override func run(sources: SequenceGenerator) -> Disposable { + let triggerSubscription = _handler.subscribe(_notifier.asObserver()) + let superSubscription = super.run(sources) + return StableCompositeDisposable.create(superSubscription, triggerSubscription) + } +} + +class RetryWhenSequence : Producer { + typealias Element = S.Generator.Element.E + + private let _sources: S + private let _notificationHandler: Observable -> TriggerObservable + + init(sources: S, notificationHandler: Observable -> TriggerObservable) { + _sources = sources + _notificationHandler = notificationHandler + } + + override func run(observer: O) -> Disposable { + let sink = RetryWhenSequenceSink(parent: self, observer: observer) + sink.disposable = sink.run((self._sources.generate(), nil)) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift new file mode 100644 index 00000000000..ef13f13ff70 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift @@ -0,0 +1,129 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = SampleType + + typealias Parent = SampleSequenceSink + + private let _parent: Parent + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + if let element = _parent._element { + if _parent._parent._onlyNew { + _parent._element = nil + } + + _parent.forwardOn(.Next(element)) + } + + if _parent._atEnd { + _parent.forwardOn(.Completed) + _parent.dispose() + } + case .Error(let e): + _parent.forwardOn(.Error(e)) + _parent.dispose() + case .Completed: + if let element = _parent._element { + _parent._element = nil + _parent.forwardOn(.Next(element)) + } + if _parent._atEnd { + _parent.forwardOn(.Completed) + _parent.dispose() + } + } + } +} + +class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias Parent = Sample + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + private var _element = nil as Element? + private var _atEnd = false + + private let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + _sourceSubscription.disposable = _parent._source.subscribe(self) + let samplerSubscription = _parent._sampler.subscribe(SamplerSink(parent: self)) + + return StableCompositeDisposable.create(_sourceSubscription, samplerSubscription) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _element = element + case .Error: + forwardOn(event) + dispose() + case .Completed: + _atEnd = true + _sourceSubscription.dispose() + } + } + +} + +class Sample : Producer { + private let _source: Observable + private let _sampler: Observable + private let _onlyNew: Bool + + init(source: Observable, sampler: Observable, onlyNew: Bool) { + _source = source + _sampler = sampler + _onlyNew = onlyNew + } + + override func run(observer: O) -> Disposable { + let sink = SampleSequenceSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift new file mode 100644 index 00000000000..bc0adc87988 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift @@ -0,0 +1,64 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ScanSink : Sink, ObserverType { + typealias Parent = Scan + typealias E = ElementType + + private let _parent: Parent + private var _accumulate: Accumulate + + init(parent: Parent, observer: O) { + _parent = parent + _accumulate = parent._seed + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let element): + do { + _accumulate = try _parent._accumulator(_accumulate, element) + forwardOn(.Next(_accumulate)) + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } + +} + +class Scan: Producer { + typealias Accumulator = (Accumulate, Element) throws -> Accumulate + + private let _source: Observable + private let _seed: Accumulate + private let _accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: Accumulator) { + _source = source + _seed = seed + _accumulator = accumulator + } + + override func run(observer: O) -> Disposable { + let sink = ScanSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift new file mode 100644 index 00000000000..0a31d9291da --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift @@ -0,0 +1,58 @@ +// +// Sequence.swift +// Rx +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SequenceSink : Sink { + typealias Parent = Sequence + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler!.scheduleRecursive((0, _parent._elements)) { (state, recurse) in + if state.0 < state.1.count { + self.forwardOn(.Next(state.1[state.0])) + recurse((state.0 + 1, state.1)) + } + else { + self.forwardOn(.Completed) + } + } + } +} + +class Sequence : Producer { + private let _elements: [E] + private let _scheduler: ImmediateSchedulerType? + + init(elements: [E], scheduler: ImmediateSchedulerType?) { + _elements = elements + _scheduler = scheduler + } + + override func subscribe(observer: O) -> Disposable { + // optimized version without scheduler + guard _scheduler != nil else { + for element in _elements { + observer.on(.Next(element)) + } + + observer.on(.Completed) + return NopDisposable.instance + } + + let sink = SequenceSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift new file mode 100644 index 00000000000..52cb5ebe3df --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift @@ -0,0 +1,101 @@ +// +// ShareReplay1.swift +// Rx +// +// Created by Krunoslav Zaher on 10/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// optimized version of share replay for most common case +final class ShareReplay1 + : Observable + , ObserverType + , SynchronizedUnsubscribeType { + + typealias DisposeKey = Bag>.KeyType + + private let _source: Observable + + private var _lock = NSRecursiveLock() + + private var _connection: SingleAssignmentDisposable? + private var _element: Element? + private var _stopped = false + private var _stopEvent = nil as Event? + private var _observers = Bag>() + + init(source: Observable) { + self._source = source + } + + override func subscribe(observer: O) -> Disposable { + _lock.lock(); defer { _lock.unlock() } + return _synchronized_subscribe(observer) + } + + func _synchronized_subscribe(observer: O) -> Disposable { + if let element = self._element { + observer.on(.Next(element)) + } + + if let stopEvent = self._stopEvent { + observer.on(stopEvent) + return NopDisposable.instance + } + + let initialCount = self._observers.count + + let disposeKey = self._observers.insert(AnyObserver(observer)) + + if initialCount == 0 { + let connection = SingleAssignmentDisposable() + _connection = connection + + connection.disposable = self._source.subscribe(self) + } + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + func synchronizedUnsubscribe(disposeKey: DisposeKey) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_unsubscribe(disposeKey) + } + + func _synchronized_unsubscribe(disposeKey: DisposeKey) { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return + } + + if _observers.count == 0 { + _connection?.dispose() + _connection = nil + } + } + + func on(event: Event) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_on(event) + } + + func _synchronized_on(event: Event) { + if _stopped { + return + } + + switch event { + case .Next(let element): + _element = element + case .Error, .Completed: + _stopEvent = event + _stopped = true + _connection?.dispose() + _connection = nil + } + + _observers.on(event) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift new file mode 100644 index 00000000000..af776b1ce9e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift @@ -0,0 +1,92 @@ +// +// ShareReplay1WhileConnected.swift +// Rx +// +// Created by Krunoslav Zaher on 12/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// optimized version of share replay for most common case +final class ShareReplay1WhileConnected + : Observable + , ObserverType + , SynchronizedUnsubscribeType { + + typealias DisposeKey = Bag>.KeyType + + private let _source: Observable + + private var _lock = NSRecursiveLock() + + private var _connection: SingleAssignmentDisposable? + private var _element: Element? + private var _observers = Bag>() + + init(source: Observable) { + self._source = source + } + + override func subscribe(observer: O) -> Disposable { + _lock.lock(); defer { _lock.unlock() } + return _synchronized_subscribe(observer) + } + + func _synchronized_subscribe(observer: O) -> Disposable { + if let element = self._element { + observer.on(.Next(element)) + } + + let initialCount = self._observers.count + + let disposeKey = self._observers.insert(AnyObserver(observer)) + + if initialCount == 0 { + let connection = SingleAssignmentDisposable() + _connection = connection + + connection.disposable = self._source.subscribe(self) + } + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + func synchronizedUnsubscribe(disposeKey: DisposeKey) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_unsubscribe(disposeKey) + } + + func _synchronized_unsubscribe(disposeKey: DisposeKey) { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return + } + + if _observers.count == 0 { + _connection?.dispose() + _connection = nil + _element = nil + } + } + + func on(event: Event) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_on(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _element = element + _observers.on(event) + case .Error, .Completed: + _element = nil + _connection?.dispose() + _connection = nil + let observers = _observers + _observers = Bag() + observers.on(event) + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift new file mode 100644 index 00000000000..abf40d8d4c1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift @@ -0,0 +1,76 @@ +// +// SingleAsync.swift +// Rx +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SingleAsyncSink : Sink, ObserverType { + typealias Parent = SingleAsync + typealias E = ElementType + + private let _parent: Parent + private var _seenValue: Bool = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + let forward = try _parent._predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + forwardOn(.Error(error as ErrorType)) + dispose() + return + } + + if _seenValue == false { + _seenValue = true + forwardOn(.Next(value)) + } else { + forwardOn(.Error(RxError.MoreThanOneElement)) + dispose() + } + + case .Error: + forwardOn(event) + dispose() + case .Completed: + if (!_seenValue) { + forwardOn(.Error(RxError.NoElements)) + } else { + forwardOn(.Completed) + } + dispose() + } + } +} + +class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + _source = source + _predicate = predicate + } + + override func run(observer: O) -> Disposable { + let sink = SingleAsyncSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift new file mode 100644 index 00000000000..36b1937f814 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift @@ -0,0 +1,57 @@ +// +// Sink.swift +// Rx +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Sink : SingleAssignmentDisposable { + private let _observer: O + + init(observer: O) { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + _observer = observer + } + + final func forwardOn(event: Event) { + if disposed { + return + } + _observer.on(event) + } + + final func forwarder() -> SinkForward { + return SinkForward(forward: self) + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } +} + +class SinkForward: ObserverType { + typealias E = O.E + + private let _forward: Sink + + init(forward: Sink) { + _forward = forward + } + + func on(event: Event) { + switch event { + case .Next: + _forward._observer.on(event) + case .Error, .Completed: + _forward._observer.on(event) + _forward.dispose() + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift new file mode 100644 index 00000000000..ea977d396fe --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift @@ -0,0 +1,128 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// count version + +class SkipCountSink : Sink, ObserverType { + typealias Parent = SkipCount + typealias Element = ElementType + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: O) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + + if remaining <= 0 { + forwardOn(.Next(value)) + } + else { + remaining -= 1 + } + case .Error: + forwardOn(event) + self.dispose() + case .Completed: + forwardOn(event) + self.dispose() + } + } + +} + +class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(observer: O) -> Disposable { + let sink = SkipCountSink(parent: self, observer: observer) + sink.disposable = source.subscribe(sink) + + return sink + } +} + +// time version + +class SkipTimeSink : Sink, ObserverType { + typealias Parent = SkipTime + typealias Element = ElementType + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: O) { + self.parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if open { + forwardOn(.Next(value)) + } + case .Error: + forwardOn(event) + self.dispose() + case .Completed: + forwardOn(event) + self.dispose() + } + } + + func tick() { + open = true + } + + func run() -> Disposable { + let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { + self.tick() + return NopDisposable.instance + } + + let disposeSubscription = parent.source.subscribe(self) + + return BinaryDisposable(disposeTimer, disposeSubscription) + } +} + +class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(observer: O) -> Disposable { + let sink = SkipTimeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift new file mode 100644 index 00000000000..be3c69373f2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift @@ -0,0 +1,125 @@ +// +// SkipUntil.swift +// Rx +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias E = Other + + private let _parent: Parent + + var _lock: NSRecursiveLock { + return _parent._lock + } + + let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent + #if TRACE_RESOURCES + AtomicIncrement(&resourceCount) + #endif + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + _parent._forwardElements = true + _subscription.dispose() + case .Error(let e): + _parent.forwardOn(.Error(e)) + _parent.dispose() + case .Completed: + _subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } + #endif + +} + + +class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = ElementType + typealias Parent = SkipUntil + + let _lock = NSRecursiveLock() + private let _parent: Parent + private var _forwardElements = false + + private let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + if _forwardElements { + forwardOn(event) + } + case .Error: + forwardOn(event) + dispose() + case .Completed: + if _forwardElements { + forwardOn(event) + } + _sourceSubscription.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = _parent._source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = _parent._other.subscribe(otherObserver) + _sourceSubscription.disposable = sourceSubscription + otherObserver._subscription.disposable = otherSubscription + + return StableCompositeDisposable.create(_sourceSubscription, otherObserver._subscription) + } +} + +class SkipUntil: Producer { + + private let _source: Observable + private let _other: Observable + + init(source: Observable, other: Observable) { + _source = source + _other = other + } + + override func run(observer: O) -> Disposable { + let sink = SkipUntilSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift new file mode 100644 index 00000000000..d16304a089e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift @@ -0,0 +1,115 @@ +// +// SkipWhile.swift +// Rx +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class SkipWhileSink : Sink, ObserverType { + + typealias Parent = SkipWhile + typealias Element = ElementType + + private let _parent: Parent + private var _running = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + do { + _running = try !_parent._predicate(value) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + } + + if _running { + forwardOn(.Next(value)) + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class SkipWhileSinkWithIndex : Sink, ObserverType { + + typealias Parent = SkipWhile + typealias Element = ElementType + + private let _parent: Parent + private var _index = 0 + private var _running = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + do { + _running = try !_parent._predicateWithIndex(value, _index) + try incrementChecked(&_index) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + } + + if _running { + forwardOn(.Next(value)) + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + typealias PredicateWithIndex = (Element, Int) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate! + private let _predicateWithIndex: PredicateWithIndex! + + init(source: Observable, predicate: Predicate) { + _source = source + _predicate = predicate + _predicateWithIndex = nil + } + + init(source: Observable, predicate: PredicateWithIndex) { + _source = source + _predicate = nil + _predicateWithIndex = predicate + } + + override func run(observer: O) -> Disposable { + if let _ = _predicate { + let sink = SkipWhileSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + else { + let sink = SkipWhileSinkWithIndex(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift new file mode 100644 index 00000000000..c60cb367971 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift @@ -0,0 +1,28 @@ +// +// StartWith.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(observer: O) -> Disposable { + for e in elements { + observer.on(.Next(e)) + } + + return source.subscribe(observer) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift new file mode 100644 index 00000000000..1d461a3d620 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift @@ -0,0 +1,60 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SubscribeOnSink : Sink, ObserverType { + typealias Element = O.E + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: O) { + self.parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + cancelSchedule.disposable = parent.scheduler.schedule(()) { (_) -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return NopDisposable.instance + } + + return disposeEverything + } +} + +class SubscribeOn : Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = SubscribeOnSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift new file mode 100644 index 00000000000..2051275cc1b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift @@ -0,0 +1,193 @@ +// +// Switch.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SwitchSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = SourceType + + private let _subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + private let _innerSubscription: SerialDisposable = SerialDisposable() + + let _lock = NSRecursiveLock() + + // state + private var _stopped = false + private var _latest = 0 + private var _hasLatest = false + + override init(observer: O) { + super.init(observer: observer) + } + + func run(source: Observable) -> Disposable { + let subscription = source.subscribe(self) + _subscriptions.disposable = subscription + return StableCompositeDisposable.create(_subscriptions, _innerSubscription) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func performMap(element: SourceType) throws -> S { + abstractMethod() + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + do { + let observable = try performMap(element).asObservable() + _hasLatest = true + _latest = _latest &+ 1 + let latest = _latest + + let d = SingleAssignmentDisposable() + _innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, _self: d) + let disposable = observable.subscribe(observer) + d.disposable = disposable + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + _stopped = true + + _subscriptions.dispose() + + if !_hasLatest { + forwardOn(.Completed) + dispose() + } + } + } +} + +class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = S.E + typealias Parent = SwitchSink + + private let _parent: Parent + private let _id: Int + private let _self: Disposable + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent, id: Int, _self: Disposable) { + _parent = parent + _id = id + self._self = _self + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: break + case .Error, .Completed: + _self.dispose() + } + + if _parent._latest != _id { + return + } + + switch event { + case .Next: + _parent.forwardOn(event) + case .Error: + _parent.forwardOn(event) + _parent.dispose() + case .Completed: + _parent._hasLatest = false + if _parent._stopped { + _parent.forwardOn(event) + _parent.dispose() + } + } + } +} + +// MARK: Specializations + +final class SwitchIdentitySink : SwitchSink { + override init(observer: O) { + super.init(observer: observer) + } + + override func performMap(element: S) throws -> S { + return element + } +} + +final class MapSwitchSink : SwitchSink { + typealias Selector = SourceType throws -> S + + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element) + } +} + +// MARK: Producers + +final class Switch : Producer { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = SwitchIdentitySink(observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +final class FlatMapLatest : Producer { + typealias Selector = SourceType throws -> S + + private let _source: Observable + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = MapSwitchSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift new file mode 100644 index 00000000000..d551100476c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift @@ -0,0 +1,144 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// count version + +class TakeCountSink : Sink, ObserverType { + typealias Parent = TakeCount + typealias E = ElementType + + private let _parent: Parent + + private var _remaining: Int + + init(parent: Parent, observer: O) { + _parent = parent + _remaining = parent._count + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + + if _remaining > 0 { + _remaining -= 1 + + forwardOn(.Next(value)) + + if _remaining == 0 { + forwardOn(.Completed) + dispose() + } + } + case .Error: + forwardOn(event) + dispose() + case .Completed: + forwardOn(event) + dispose() + } + } + +} + +class TakeCount: Producer { + private let _source: Observable + private let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + _source = source + _count = count + } + + override func run(observer: O) -> Disposable { + let sink = TakeCountSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} + +// time version + +class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Parent = TakeTime + typealias E = ElementType + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let value): + forwardOn(.Next(value)) + case .Error: + forwardOn(event) + dispose() + case .Completed: + forwardOn(event) + dispose() + } + } + + func tick() { + _lock.lock(); defer { _lock.unlock() } + + forwardOn(.Completed) + dispose() + } + + func run() -> Disposable { + let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) { + self.tick() + return NopDisposable.instance + } + + let disposeSubscription = _parent._source.subscribe(self) + + return BinaryDisposable(disposeTimer, disposeSubscription) + } +} + +class TakeTime : Producer { + typealias TimeInterval = RxTimeInterval + + private let _source: Observable + private let _duration: TimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + _source = source + _scheduler = scheduler + _duration = duration + } + + override func run(observer: O) -> Disposable { + let sink = TakeTimeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift new file mode 100644 index 00000000000..2a479d393f0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift @@ -0,0 +1,63 @@ +// +// TakeLast.swift +// Rx +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + +class TakeLastSink : Sink, ObserverType { + typealias Parent = TakeLast + typealias E = ElementType + + private let _parent: Parent + + private var _elements: Queue + + init(parent: Parent, observer: O) { + _parent = parent + _elements = Queue(capacity: parent._count + 1) + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + _elements.enqueue(value) + if _elements.count > self._parent._count { + _elements.dequeue() + } + case .Error: + forwardOn(event) + dispose() + case .Completed: + for e in _elements { + forwardOn(.Next(e)) + } + forwardOn(.Completed) + dispose() + } + } +} + +class TakeLast: Producer { + private let _source: Observable + private let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + _source = source + _count = count + } + + override func run(observer: O) -> Disposable { + let sink = TakeLastSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift new file mode 100644 index 00000000000..f1e36d9774e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift @@ -0,0 +1,120 @@ +// +// TakeUntil.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias E = Other + + private let _parent: Parent + + var _lock: NSRecursiveLock { + return _parent._lock + } + + private let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + _parent.forwardOn(.Completed) + _parent.dispose() + case .Error(let e): + _parent.forwardOn(.Error(e)) + _parent.dispose() + case .Completed: + _parent._open = true + _subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } +#endif +} + +class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias E = ElementType + typealias Parent = TakeUntil + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + private var _open = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Error: + forwardOn(event) + dispose() + case .Completed: + forwardOn(event) + dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = _parent._other.subscribe(otherObserver) + otherObserver._subscription.disposable = otherSubscription + let sourceSubscription = _parent._source.subscribe(self) + + return StableCompositeDisposable.create(sourceSubscription, otherObserver._subscription) + } +} + +class TakeUntil: Producer { + + private let _source: Observable + private let _other: Observable + + init(source: Observable, other: Observable) { + _source = source + _other = other + } + + override func run(observer: O) -> Disposable { + let sink = TakeUntilSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift new file mode 100644 index 00000000000..a660bb813bb --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift @@ -0,0 +1,132 @@ +// +// TakeWhile.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TakeWhileSink + : Sink + , ObserverType { + typealias Parent = TakeWhile + typealias Element = ElementType + + private let _parent: Parent + + private var _running = true + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + return + } + + do { + _running = try _parent._predicate(value) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + + if _running { + forwardOn(.Next(value)) + } else { + forwardOn(.Completed) + dispose() + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } + +} + +class TakeWhileSinkWithIndex + : Sink + , ObserverType { + typealias Parent = TakeWhile + typealias Element = ElementType + + private let _parent: Parent + + private var _running = true + private var _index = 0 + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + return + } + + do { + _running = try _parent._predicateWithIndex(value, _index) + try incrementChecked(&_index) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + + if _running { + forwardOn(.Next(value)) + } else { + forwardOn(.Completed) + dispose() + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } + +} + +class TakeWhile: Producer { + typealias Predicate = (Element) throws -> Bool + typealias PredicateWithIndex = (Element, Int) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate! + private let _predicateWithIndex: PredicateWithIndex! + + init(source: Observable, predicate: Predicate) { + _source = source + _predicate = predicate + _predicateWithIndex = nil + } + + init(source: Observable, predicate: PredicateWithIndex) { + _source = source + _predicate = nil + _predicateWithIndex = predicate + } + + override func run(observer: O) -> Disposable { + if let _ = _predicate { + let sink = TakeWhileSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } else { + let sink = TakeWhileSinkWithIndex(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift new file mode 100644 index 00000000000..33e9837dc4b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift @@ -0,0 +1,104 @@ +// +// Throttle.swift +// Rx +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias ParentType = Throttle + + private let _parent: ParentType + + let _lock = NSRecursiveLock() + + // state + private var _id = 0 as UInt64 + private var _value: Element? = nil + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: O) { + _parent = parent + + super.init(observer: observer) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribe(self) + + return StableCompositeDisposable.create(subscription, cancellable) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _id = _id &+ 1 + let currentId = _id + _value = element + + + let scheduler = _parent._scheduler + let dueTime = _parent._dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.disposable = scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate) + case .Error: + _value = nil + forwardOn(event) + dispose() + case .Completed: + if let value = _value { + _value = nil + forwardOn(.Next(value)) + } + forwardOn(.Completed) + dispose() + } + } + + func propagate(currentId: UInt64) -> Disposable { + _lock.lock(); defer { _lock.unlock() } // { + let originalValue = _value + + if let value = originalValue where _id == currentId { + _value = nil + forwardOn(.Next(value)) + } + // } + return NopDisposable.instance + } +} + +class Throttle : Producer { + + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = ThrottleSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift new file mode 100644 index 00000000000..fe6a1b85396 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift @@ -0,0 +1,120 @@ +// +// Timeout.swift +// Rx +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias E = ElementType + typealias Parent = Timeout + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + private let _timerD = SerialDisposable() + private let _subscription = SerialDisposable() + + private var _id = 0 + private var _switched = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + _subscription.disposable = original + + _createTimeoutTimer() + + original.disposable = _parent._source.subscribeSafe(self) + + return StableCompositeDisposable.create(_subscription, _timerD) + } + + func on(event: Event) { + switch event { + case .Next: + var onNextWins = false + + _lock.performLocked() { + onNextWins = !self._switched + if onNextWins { + self._id = self._id &+ 1 + } + } + + if onNextWins { + forwardOn(event) + self._createTimeoutTimer() + } + case .Error, .Completed: + var onEventWins = false + + _lock.performLocked() { + onEventWins = !self._switched + if onEventWins { + self._id = self._id &+ 1 + } + } + + if onEventWins { + forwardOn(event) + self.dispose() + } + } + } + + private func _createTimeoutTimer() { + if _timerD.disposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + _timerD.disposable = nextTimer + + nextTimer.disposable = _parent._scheduler.scheduleRelative(_id, dueTime: _parent._dueTime) { state in + + var timerWins = false + + self._lock.performLocked() { + self._switched = (state == self._id) + timerWins = self._switched + } + + if timerWins { + self._subscription.disposable = self._parent._other.subscribeSafe(self.forwarder()) + } + + return NopDisposable.instance + } + } +} + + +class Timeout : Producer { + + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _other: Observable + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _other = other + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = TimeoutSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift new file mode 100644 index 00000000000..dcbb2bfd260 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift @@ -0,0 +1,72 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TimerSink : Sink { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.schedulePeriodic(0 as O.E, startAfter: _parent._dueTime, period: _parent._period!) { state in + self.forwardOn(.Next(state)) + return state &+ 1 + } + } +} + +class TimerOneOffSink : Sink { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRelative((), dueTime: _parent._dueTime) { (_) -> Disposable in + self.forwardOn(.Next(0)) + self.forwardOn(.Completed) + + return NopDisposable.instance + } + } +} + +class Timer: Producer { + private let _scheduler: SchedulerType + private let _dueTime: RxTimeInterval + private let _period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + _scheduler = scheduler + _dueTime = dueTime + _period = period + } + + override func run(observer: O) -> Disposable { + if let _ = _period { + let sink = TimerSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift new file mode 100644 index 00000000000..cb5c428143c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift @@ -0,0 +1,50 @@ +// +// ToArray.swift +// Rx +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ToArraySink : Sink, ObserverType { + typealias Parent = ToArray + + let _parent: Parent + var _list = Array() + + init(parent: Parent, observer: O) { + _parent = parent + + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + self._list.append(value) + case .Error(let e): + forwardOn(.Error(e)) + self.dispose() + case .Completed: + forwardOn(.Next(_list)) + forwardOn(.Completed) + self.dispose() + } + } +} + +class ToArray : Producer<[SourceType]> { + let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = ToArraySink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift new file mode 100644 index 00000000000..6aa229823ca --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift @@ -0,0 +1,78 @@ +// +// Using.swift +// Rx +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class UsingSink : Sink, ObserverType { + + typealias Parent = Using + typealias E = O.E + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + var disposable = NopDisposable.instance + + do { + let resource = try _parent._resourceFactory() + disposable = resource + let source = try _parent._observableFactory(resource) + + return StableCompositeDisposable.create( + source.subscribe(self), + disposable + ) + } catch let error { + return StableCompositeDisposable.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(event: Event) { + switch event { + case let .Next(value): + forwardOn(.Next(value)) + case let .Error(error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } +} + +class Using: Producer { + + typealias E = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = ResourceType throws -> Observable + + private let _resourceFactory: ResourceFactory + private let _observableFactory: ObservableFactory + + + init(resourceFactory: ResourceFactory, observableFactory: ObservableFactory) { + _resourceFactory = resourceFactory + _observableFactory = observableFactory + } + + override func run(observer: O) -> Disposable { + let sink = UsingSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift new file mode 100644 index 00000000000..24060a8493e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift @@ -0,0 +1,152 @@ +// +// Window.swift +// Rx +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class WindowTimeCountSink> + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = WindowTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + private var _subject = PublishSubject() + private var _count = 0 + private var _windowId = 0 + + private let _timerD = SerialDisposable() + private let _refCountDisposable: RefCountDisposable + private let _groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + + _groupDisposable.addDisposable(_timerD) + + _refCountDisposable = RefCountDisposable(disposable: _groupDisposable) + super.init(observer: observer) + } + + func run() -> Disposable { + + forwardOn(.Next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) + createTimer(_windowId) + + _groupDisposable.addDisposable(_parent._source.subscribeSafe(self)) + return _refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + _subject.on(.Completed) + _subject = PublishSubject() + + forwardOn(.Next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .Next(let element): + _subject.on(.Next(element)) + + do { + try incrementChecked(&_count) + } catch (let e) { + _subject.on(.Error(e as ErrorType)) + dispose() + } + + if (_count == _parent._count) { + newWindow = true + _count = 0 + _windowId += 1 + newId = _windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .Error(let error): + _subject.on(.Error(error)) + forwardOn(.Error(error)) + dispose() + case .Completed: + _subject.on(.Completed) + forwardOn(.Completed) + dispose() + } + + if newWindow { + createTimer(newId) + } + } + + func createTimer(windowId: Int) { + if _timerD.disposed { + return + } + + if _windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + _timerD.disposable = nextTimer + + nextTimer.disposable = _parent._scheduler.scheduleRelative(windowId, dueTime: _parent._timeSpan) { previousWindowId in + + var newId = 0 + + self._lock.performLocked { + if previousWindowId != self._windowId { + return + } + + self._count = 0 + self._windowId = self._windowId &+ 1 + newId = self._windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return NopDisposable.instance + } + } +} + +class WindowTimeCount : Producer> { + + private let _timeSpan: RxTimeInterval + private let _count: Int + private let _scheduler: SchedulerType + private let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + _source = source + _timeSpan = timeSpan + _count = count + _scheduler = scheduler + } + + override func run>(observer: O) -> Disposable { + let sink = WindowTimeCountSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift new file mode 100644 index 00000000000..7d0ab9f615c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift @@ -0,0 +1,122 @@ +// +// WithLatestFrom.swift +// RxExample +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias Parent = WithLatestFrom + typealias E = FirstType + + private let _parent: Parent + + var _lock = NSRecursiveLock() + private var _latest: SecondType? + + init(parent: Parent, observer: O) { + _parent = parent + + super.init(observer: observer) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.disposable = _parent._second.subscribe(sndO) + let fstSubscription = _parent._first.subscribe(self) + + return StableCompositeDisposable.create(fstSubscription, sndSubscription) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case let .Next(value): + guard let latest = _latest else { return } + do { + let res = try _parent._resultSelector(value, latest) + + forwardOn(.Next(res)) + } catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Completed: + forwardOn(.Completed) + dispose() + case let .Error(error): + forwardOn(.Error(error)) + dispose() + } + } +} + +class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias Parent = WithLatestFromSink + typealias E = SecondType + + private let _parent: Parent + private let _disposable: Disposable + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent, disposable: Disposable) { + _parent = parent + _disposable = disposable + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case let .Next(value): + _parent._latest = value + case .Completed: + _disposable.dispose() + case let .Error(error): + _parent.forwardOn(.Error(error)) + _parent.dispose() + } + } +} + +class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + private let _first: Observable + private let _second: Observable + private let _resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: ResultSelector) { + _first = first + _second = second + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = WithLatestFromSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift new file mode 100644 index 00000000000..d083a30a582 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift @@ -0,0 +1,137 @@ +// +// Zip+CollectionType.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ZipCollectionTypeSink + : Sink { + typealias Parent = ZipCollectionType + typealias SourceElement = C.Generator.Element.E + + private let _parent: Parent + + private let _lock = NSRecursiveLock() + + // state + private var _numberOfValues = 0 + private var _values: [Queue] + private var _isDone: [Bool] + private var _numberOfDone = 0 + private var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O) { + _parent = parent + _values = [Queue](count: parent.count, repeatedValue: Queue(capacity: 4)) + _isDone = [Bool](count: parent.count, repeatedValue: false) + _subscriptions = Array() + _subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + _subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer) + } + + func on(event: Event, atIndex: Int) { + _lock.lock(); defer { _lock.unlock() } // { + switch event { + case .Next(let element): + _values[atIndex].enqueue(element) + + if _values[atIndex].count == 1 { + _numberOfValues += 1 + } + + if _numberOfValues < _parent.count { + let numberOfOthersThatAreDone = _numberOfDone - (_isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == _parent.count - 1 { + self.forwardOn(.Completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(_parent.count) + + // recalculate number of values + _numberOfValues = 0 + + for i in 0 ..< _values.count { + arguments.append(_values[i].dequeue()!) + if _values[i].count > 0 { + _numberOfValues += 1 + } + } + + let result = try _parent.resultSelector(arguments) + self.forwardOn(.Next(result)) + } + catch let error { + self.forwardOn(.Error(error)) + self.dispose() + } + + case .Error(let error): + self.forwardOn(.Error(error)) + self.dispose() + case .Completed: + if _isDone[atIndex] { + return + } + + _isDone[atIndex] = true + _numberOfDone += 1 + + if _numberOfDone == _parent.count { + self.forwardOn(.Completed) + self.dispose() + } + else { + _subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in _parent.sources.startIndex ..< _parent.sources.endIndex { + let index = j + let source = _parent.sources[i].asObservable() + _subscriptions[j].disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + j += 1 + } + + return CompositeDisposable(disposables: _subscriptions.map { $0 }) + } +} + +class ZipCollectionType : Producer { + typealias ResultSelector = [C.Generator.Element.E] throws -> R + + let sources: C + let resultSelector: ResultSelector + let count: Int + + init(sources: C, resultSelector: ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = Int(self.sources.count.toIntMax()) + } + + override func run(observer: O) -> Disposable { + let sink = ZipCollectionTypeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift new file mode 100644 index 00000000000..891c2c40ca3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift @@ -0,0 +1,829 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + + +// 2 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, resultSelector: (O1.E, O2.E) throws -> E) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink2_ : ZipSink { + typealias R = O.E + typealias Parent = Zip2 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 2, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!) + } +} + +class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let source1: Observable + let source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink2_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 3 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, resultSelector: (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink3_ : ZipSink { + typealias R = O.E + typealias Parent = Zip3 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 3, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!) + } +} + +class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink3_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 4 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink4_ : ZipSink { + typealias R = O.E + typealias Parent = Zip4 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 4, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!) + } +} + +class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink4_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 5 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink5_ : ZipSink { + typealias R = O.E + typealias Parent = Zip5 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 5, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!) + } +} + +class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink5_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 6 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink6_ : ZipSink { + typealias R = O.E + typealias Parent = Zip6 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 6, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + subscription6.disposable = _parent.source6.subscribe(observer6) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!) + } +} + +class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink6_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 7 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink7_ : ZipSink { + typealias R = O.E + typealias Parent = Zip7 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 7, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + case 6: return _values7.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: _lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + subscription6.disposable = _parent.source6.subscribe(observer6) + subscription7.disposable = _parent.source7.subscribe(observer7) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!, _values7.dequeue()!) + } +} + +class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink7_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 8 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink8_ : ZipSink { + typealias R = O.E + typealias Parent = Zip8 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + var _values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 8, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + case 6: return _values7.count > 0 + case 7: return _values8.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: _lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: _lock, parent: self, index: 7, setNextValue: { self._values8.enqueue($0) }, this: subscription8) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + subscription6.disposable = _parent.source6.subscribe(observer6) + subscription7.disposable = _parent.source7.subscribe(observer7) + subscription8.disposable = _parent.source8.subscribe(observer8) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!, _values7.dequeue()!, _values8.dequeue()!) + } +} + +class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink8_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift new file mode 100644 index 00000000000..108326517e9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift @@ -0,0 +1,157 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol ZipSinkProtocol : class +{ + func next(index: Int) + func fail(error: ErrorType) + func done(index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = O.E + + let _arity: Int + + let _lock = NSRecursiveLock() + + // state + private var _isDone: [Bool] + + init(arity: Int, observer: O) { + _isDone = [Bool](count: arity, repeatedValue: false) + _arity = arity + + super.init(observer: observer) + } + + func getResult() throws -> Element { + abstractMethod() + } + + func hasElements(index: Int) -> Bool { + abstractMethod() + } + + func next(index: Int) { + var hasValueAll = true + + for i in 0 ..< _arity { + if !hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try getResult() + self.forwardOn(.Next(result)) + } + catch let e { + self.forwardOn(.Error(e)) + dispose() + } + } + else { + var allOthersDone = true + + let arity = _isDone.count + for i in 0 ..< arity { + if i != index && !_isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + forwardOn(.Completed) + self.dispose() + } + } + } + + func fail(error: ErrorType) { + forwardOn(.Error(error)) + dispose() + } + + func done(index: Int) { + _isDone[index] = true + + var allDone = true + + for done in _isDone { + if !done { + allDone = false + break + } + } + + if allDone { + forwardOn(.Completed) + dispose() + } + } +} + +class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = ElementType + typealias ValueSetter = (ElementType) -> () + + private var _parent: ZipSinkProtocol? + + let _lock: NSRecursiveLock + + // state + private let _index: Int + private let _this: Disposable + private let _setNextValue: ValueSetter + + init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: ValueSetter, this: Disposable) { + _lock = lock + _parent = parent + _index = index + _this = this + _setNextValue = setNextValue + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + if let _ = _parent { + switch event { + case .Next(_): + break + case .Error(_): + _this.dispose() + case .Completed: + _this.dispose() + } + } + + if let parent = _parent { + switch event { + case .Next(let value): + _setNextValue(value) + parent.next(_index) + case .Error(let error): + parent.fail(error) + case .Completed: + parent.done(_index) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift new file mode 100644 index 00000000000..8613eb5a62f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift @@ -0,0 +1,64 @@ +// +// Observable+Aggregate.swift +// Rx +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: reduce + +extension ObservableType { + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func reduce(seed: A, accumulator: (A, E) throws -> A, mapResult: (A) throws -> R) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func reduce(seed: A, accumulator: (A, E) throws -> A) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } + + /** + Converts an Observable into another Observable that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: An observable sequence containing all the emitted elements as array. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func toArray() + -> Observable<[E]> { + return ToArray(source: self.asObservable()) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift new file mode 100644 index 00000000000..8e91eb3c0aa --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift @@ -0,0 +1,190 @@ +// +// Observable+Binding.swift +// Rx +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: multicast + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func multicast(subject: S) + -> ConnectableObservable { + return ConnectableObservableAdapter(source: self.asObservable(), subject: subject) + } + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func multicast(subjectSelector: () throws -> S, selector: (Observable) throws -> Observable) + -> Observable { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +// MARK: publish + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func publish() -> ConnectableObservable { + return self.multicast(PublishSubject()) + } +} + +// MARK: replay + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func replay(bufferSize: Int) + -> ConnectableObservable { + return self.multicast(ReplaySubject.create(bufferSize: bufferSize)) + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func replayAll() + -> ConnectableObservable { + return self.multicast(ReplaySubject.createUnbounded()) + } +} + +// MARK: refcount + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refCount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func refCount() -> Observable { + return RefCount(source: self) + } +} + +// MARK: share + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [share operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func share() -> Observable { + return self.publish().refCount() + } +} + +// MARK: shareReplay + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func shareReplay(bufferSize: Int) + -> Observable { + if bufferSize == 1 { + return ShareReplay1(source: self.asObservable()) + } + else { + return self.replay(bufferSize).refCount() + } + } + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + Unlike `shareReplay(bufferSize: Int)`, this operator will clear latest element from replay buffer in case number of subscribers drops from one to zero. In case sequence + completes or errors out replay buffer is also cleared. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func shareReplayLatestWhileConnected() + -> Observable { + return ShareReplay1WhileConnected(source: self.asObservable()) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift new file mode 100644 index 00000000000..f8875a53c50 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift @@ -0,0 +1,62 @@ +// +// Observable+Concurrency.swift +// Rx +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: observeOn + +extension ObservableType { + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func observeOn(scheduler: ImmediateSchedulerType) + -> Observable { + if let scheduler = scheduler as? SerialDispatchQueueScheduler { + return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler) + } + else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + } +} + +// MARK: subscribeOn + +extension ObservableType { + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func subscribeOn(scheduler: ImmediateSchedulerType) + -> Observable { + return SubscribeOn(source: self, scheduler: scheduler) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift new file mode 100644 index 00000000000..acd3b8e5b9f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift @@ -0,0 +1,219 @@ +// +// Observable+Creation.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Observable { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func create(subscribe: (AnyObserver) -> Disposable) -> Observable { + return AnonymousObservable(subscribe) + } + + // MARK: empty + + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func empty() -> Observable { + return Empty() + } + + // MARK: never + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func never() -> Observable { + return Never() + } + + // MARK: just + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func just(element: E) -> Observable { + return Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func just(element: E, scheduler: ImmediateSchedulerType) -> Observable { + return JustScheduled(element: element, scheduler: scheduler) + } + + // MARK: fail + + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func error(error: ErrorType) -> Observable { + return Error(error: error) + } + + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func of(elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable { + return Sequence(elements: elements, scheduler: scheduler) + } + + // MARK: defer + + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func deferred(observableFactory: () throws -> Observable) + -> Observable { + return Deferred(observableFactory: observableFactory) + } + + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func generate(initialState initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable { + return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } + + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func repeatElement(element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RepeatElement(element: element, scheduler: scheduler) + } + + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func using(resourceFactory: () throws -> R, observableFactory: R throws -> Observable) -> Observable { + return Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +extension Observable where Element : SignedIntegerType { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func range(start start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +extension SequenceType { + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable { + return Sequence(elements: Array(self), scheduler: scheduler) + } +} + +extension Array { + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable { + return Sequence(elements: self, scheduler: scheduler) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift new file mode 100644 index 00000000000..5d058789b81 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift @@ -0,0 +1,28 @@ +// +// Observable+Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: debug + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - returns: An observable sequence whose events are printed to standard output. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func debug(identifier: String? = nil, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self.asObservable(), identifier: identifier, file: file, line: line, function: function) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift new file mode 100644 index 00000000000..ae2bf50be73 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift @@ -0,0 +1,330 @@ +// +// Observable+Multiple.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: combineLatest + +extension CollectionType where Generator.Element : ObservableType { + + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func combineLatest(resultSelector: [Generator.Element.E] throws -> R) -> Observable { + return CombineLatestCollectionType(sources: self, resultSelector: resultSelector) + } +} + +// MARK: zip + +extension CollectionType where Generator.Element : ObservableType { + + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func zip(resultSelector: [Generator.Element.E] throws -> R) -> Observable { + return ZipCollectionType(sources: self, resultSelector: resultSelector) + } +} + +// MARK: switch + +extension ObservableType where E : ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func switchLatest() -> Observable { + return Switch(source: asObservable()) + } +} + +// MARK: concat + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat(second: O) -> Observable { + return [asObservable(), second.asObservable()].concat() + } +} + +extension SequenceType where Generator.Element : ObservableType { + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat() + -> Observable { + return Concat(sources: self, count: nil) + } +} + +extension CollectionType where Generator.Element : ObservableType { + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow and enable generating + infinite observable sequences while using limited amount of memory during generation. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat() + -> Observable { + return Concat(sources: self, count: self.count.toIntMax()) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat() -> Observable { + return merge(maxConcurrent: 1) + } +} + +// MARK: merge + +extension ObservableType where E : ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func merge() -> Observable { + return Merge(source: asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func merge(maxConcurrent maxConcurrent: Int) + -> Observable { + return MergeLimited(source: asObservable(), maxConcurrent: maxConcurrent) + } +} + +// MARK: catch + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func catchError(handler: (ErrorType) throws -> Observable) + -> Observable { + return Catch(source: asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func catchErrorJustReturn(element: E) + -> Observable { + return Catch(source: asObservable(), handler: { _ in Observable.just(element) }) + } + +} + +extension SequenceType where Generator.Element : ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func catchError() + -> Observable { + return CatchSequence(sources: self) + } +} + +// MARK: takeUntil + +extension ObservableType { + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeUntil(other: O) + -> Observable { + return TakeUntil(source: asObservable(), other: other.asObservable()) + } +} + +// MARK: skipUntil + +extension ObservableType { + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skipUntil(other: O) + -> Observable { + return SkipUntil(source: asObservable(), other: other.asObservable()) + } +} + +// MARK: amb + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func amb + (right: O2) + -> Observable { + return Amb(left: asObservable(), right: right.asObservable()) + } +} + +extension SequenceType where Generator.Element : ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func amb() + -> Observable { + return self.reduce(Observable.never()) { a, o in + return a.amb(o.asObservable()) + } + } +} + +// withLatestFrom + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(second: SecondO, resultSelector: (E, SecondO.E) throws -> ResultType) -> Observable { + return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(second: SecondO) -> Observable { + return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift new file mode 100644 index 00000000000..088fb61f183 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift @@ -0,0 +1,258 @@ +// +// Observable+Single.swift +// Rx +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: distinct until changed + +extension ObservableType where E: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged() + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged(keySelector: (E) throws -> K) + -> Observable { + return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged(comparer: (lhs: E, rhs: E) throws -> Bool) + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged(keySelector: (E) throws -> K, comparer: (lhs: K, rhs: K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } +} + +// MARK: doOn + +extension ObservableType { + + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter eventHandler: Action to invoke for each event in the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOn(eventHandler: (Event) throws -> Void) + -> Observable { + return Do(source: self.asObservable(), eventHandler: eventHandler) + } + + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOn(onNext onNext: (E throws -> Void)? = nil, onError: (ErrorType throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable()) { e in + switch e { + case .Next(let element): + try onNext?(element) + case .Error(let e): + try onError?(e) + case .Completed: + try onCompleted?() + } + } + } + + /** + Invokes an action for each Next event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOnNext(onNext: (E throws -> Void)) + -> Observable { + return self.doOn(onNext: onNext) + } + + /** + Invokes an action for the Error event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOnError(onError: (ErrorType throws -> Void)) + -> Observable { + return self.doOn(onError: onError) + } + + /** + Invokes an action for the Completed event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOnCompleted(onCompleted: (() throws -> Void)) + -> Observable { + return self.doOn(onCompleted: onCompleted) + } +} + +// MARK: startWith + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func startWith(elements: E ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +// MARK: retry + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retry() -> Observable { + return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retry(maxAttemptCount: Int) + -> Observable { + return CatchSequence(sources: Repeat(count: maxAttemptCount, repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retryWhen(notificationHandler: Observable -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retryWhen(notificationHandler: Observable -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +// MARK: scan + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func scan(seed: A, accumulator: (A, E) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift new file mode 100644 index 00000000000..96fe5fe24ec --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift @@ -0,0 +1,323 @@ +// +// Observable+StandardSequenceOperators.swift +// Rx +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: filter aka where + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func filter(predicate: (E) throws -> Bool) + -> Observable { + return Filter(source: asObservable(), predicate: predicate) + } +} + +// MARK: takeWhile + +extension ObservableType { + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeWhile(predicate: (E) throws -> Bool) + -> Observable { + return TakeWhile(source: asObservable(), predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + The element's index is used in the logic of the predicate function. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeWhileWithIndex(predicate: (E, Int) throws -> Bool) + -> Observable { + return TakeWhile(source: asObservable(), predicate: predicate) + } +} + +// MARK: take + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func take(count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: asObservable(), count: count) + } + } +} + +// MARK: takeLast + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeLast(count: Int) + -> Observable { + return TakeLast(source: asObservable(), count: count) + } +} + + +// MARK: skip + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skip(count: Int) + -> Observable { + return SkipCount(source: asObservable(), count: count) + } +} + +// MARK: SkipWhile + +extension ObservableType { + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skipWhile(predicate: (E) throws -> Bool) -> Observable { + return SkipWhile(source: asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + The element's index is used in the logic of the predicate function. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skipWhileWithIndex(predicate: (E, Int) throws -> Bool) -> Observable { + return SkipWhile(source: asObservable(), predicate: predicate) + } +} + +// MARK: map aka select + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter selector: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func map(selector: E throws -> R) + -> Observable { + return self.asObservable().composeMap(selector) + } + + /** + Projects each element of an observable sequence into a new form by incorporating the element's index. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func mapWithIndex(selector: (E, Int) throws -> R) + -> Observable { + return MapWithIndex(source: asObservable(), selector: selector) + } +} + +// MARK: flatMap + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMap(selector: (E) throws -> O) + -> Observable { + return FlatMap(source: asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMapWithIndex(selector: (E, Int) throws -> O) + -> Observable { + return FlatMapWithIndex(source: asObservable(), selector: selector) + } +} + +// MARK: flatMapFirst + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMapFirst(selector: (E) throws -> O) + -> Observable { + return FlatMapFirst(source: asObservable(), selector: selector) + } +} + +// MARK: flatMapLatest + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMapLatest(selector: (E) throws -> O) + -> Observable { + return FlatMapLatest(source: asObservable(), selector: selector) + } +} + +// MARK: elementAt + +extension ObservableType { + + /** + Returns a sequence emitting only item _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required item (starting from 0). + - returns: An observable sequence that emits the desired item as its own sole emission. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func elementAt(index: Int) + -> Observable { + return ElementAt(source: asObservable(), index: index, throwOnEmpty: true) + } +} + +// MARK: single + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one item before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single item or throws an exception if more (or none) of them are emitted. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func single() + -> Observable { + return SingleAsync(source: asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one item before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single item or throws an exception if more (or none) of them are emitted. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func single(predicate: (E) throws -> Bool) + -> Observable { + return SingleAsync(source: asObservable(), predicate: predicate) + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift new file mode 100644 index 00000000000..d1c93be0eb2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift @@ -0,0 +1,274 @@ +// +// Observable+Time.swift +// Rx +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: throttle +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + `throttle` and `debounce` are synonyms. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers and send events on. + - returns: The throttled sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func throttle(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + `throttle` and `debounce` are synonyms. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers and send events on. + - returns: The throttled sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func debounce(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +// MARK: sample + +extension ObservableType { + + /** + Samples the source observable sequence using a samper observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - returns: Sampled observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func sample(sampler: O) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true) + } +} + +extension Observable where Element : SignedIntegerType { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func interval(period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer(dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +// MARK: timer + +extension Observable where Element: SignedIntegerType { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func timer(dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +// MARK: take + +extension ObservableType { + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func take(duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// MARK: skip + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skip(duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// MARK: ignoreElements + +extension ObservableType { + + /** + Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func ignoreElements() + -> Observable { + return filter { _ -> Bool in + return false + } + } +} + +// MARK: delaySubscription + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func delaySubscription(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +// MARK: buffer + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func buffer(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[E]> { + return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +// MARK: window + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func window(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +// MARK: timeout + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a TimeoutError in case of a timeout. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func timeout(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.Timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func timeout(dueTime: RxTimeInterval, other: O, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 00000000000..5a7f3341e44 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,56 @@ +// +// ObserverType.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Supports push-style iteration over an observable sequence. +*/ +public protocol ObserverType { + /** + The type of elements in sequence that observer can observe. + */ + associatedtype E + + /** + Notify observer about sequence event. + + - parameter event: Event that occurred. + */ + func on(event: Event) +} + +/** +Convenience API extensions to provide alternate next, error, completed events +*/ +public extension ObserverType { + + /** + Convenience method equivalent to `on(.Next(element: E))` + + - parameter element: Next element to send to observer(s) + */ + final func onNext(element: E) { + on(.Next(element)) + } + + /** + Convenience method equivalent to `on(.Completed)` + */ + final func onCompleted() { + on(.Completed) + } + + /** + Convenience method equivalent to `on(.Error(error: ErrorType))` + - parameter error: ErrorType to send to observer(s) + */ + final func onError(error: ErrorType) { + on(.Error(error)) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 00000000000..2bb8f0a4891 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,34 @@ +// +// AnonymousObserver.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class AnonymousObserver : ObserverBase { + typealias Element = ElementType + + typealias EventHandler = Event -> Void + + private let _eventHandler : EventHandler + + init(_ eventHandler: EventHandler) { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + _eventHandler = eventHandler + } + + override func onCore(event: Event) { + return _eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } +#endif +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 00000000000..0795952162e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,39 @@ +// +// ObserverBase.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ObserverBase : Disposable, ObserverType { + typealias E = ElementType + + private var _isStopped: AtomicInt = 0 + + func on(event: Event) { + switch event { + case .Next: + if _isStopped == 0 { + onCore(event) + } + case .Error, .Completed: + + if !AtomicCompareAndSwap(0, 1, &_isStopped) { + return + } + + onCore(event) + } + } + + func onCore(event: Event) { + abstractMethod() + } + + func dispose() { + _isStopped = 1 + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 00000000000..1afecb46209 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +enum TailRecursiveSinkCommand { + case MoveNext + case Dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType { + typealias Value = TailRecursiveSinkCommand + typealias E = O.E + typealias SequenceGenerator = (generator: S.Generator, remaining: IntMax?) + + var _generators: [SequenceGenerator] = [] + var _disposed = false + var _subscription = SerialDisposable() + + // this is thread safe object + var _gate = AsyncLock>>() + + override init(observer: O) { + super.init(observer: observer) + } + + func run(sources: SequenceGenerator) -> Disposable { + _generators.append(sources) + + schedule(.MoveNext) + + return _subscription + } + + func invoke(command: TailRecursiveSinkCommand) { + switch command { + case .Dispose: + disposeCommand() + case .MoveNext: + moveNextCommand() + } + } + + // simple implementation for now + func schedule(command: TailRecursiveSinkCommand) { + _gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + forwardOn(.Completed) + dispose() + } + + func extract(observable: Observable) -> SequenceGenerator? { + abstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? = nil + + repeat { + guard let (g, left) = _generators.last else { + break + } + + if _disposed { + return + } + + _generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + _generators.append((e, knownOriginalLeft - 1)) + } + } + else { + _generators.append((e, nil)) + } + + let nextGenerator = extract(nextCandidate) + + if let nextGenerator = nextGenerator { + _generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < _generators.count { + maxTailRecursiveSinkStackSize = _generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + if next == nil { + done() + return + } + + let disposable = SingleAssignmentDisposable() + _subscription.disposable = disposable + disposable.disposable = subscribeToNext(next!) + } + + func subscribeToNext(source: Observable) -> Disposable { + abstractMethod() + } + + func disposeCommand() { + _disposed = true + _generators.removeAll(keepCapacity: false) + } + + override func dispose() { + super.dispose() + + _subscription.dispose() + + schedule(.Dispose) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 00000000000..418c9b163b2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,45 @@ +// +// Platform.Darwin.swift +// Rx +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + #if TRACE_RESOURCES + public typealias AtomicInt = Int32 + #else + typealias AtomicInt = Int32 + #endif + + let AtomicCompareAndSwap = OSAtomicCompareAndSwap32 + let AtomicIncrement = OSAtomicIncrement32 + let AtomicDecrement = OSAtomicDecrement32 + + extension NSThread { + static func setThreadLocalStorageValue(value: T?, forKey key: protocol) { + let currentThread = NSThread.currentThread() + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary.setObject(newValue, forKey: key) + } + else { + threadDictionary.removeObjectForKey(key) + } + + } + static func getThreadLocalStorageValueForKey(key: protocol) -> T? { + let currentThread = NSThread.currentThread() + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 00000000000..f5b93681cd0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,222 @@ +// +// Platform.Linux.swift +// Rx +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + //////////////////////////////////////////////////////////////////////////////// + // This is not the greatest API in the world, this is just a tribute. + // !!! Proof of concept until libdispatch becomes operational. !!! + //////////////////////////////////////////////////////////////////////////////// + + import Foundation + import XCTest + import Glibc + import SwiftShims + + // MARK: CoreFoundation run loop mock + + public typealias CFRunLoopRef = Int + public let kCFRunLoopDefaultMode = "CFRunLoopDefaultMode" + + typealias Action = () -> () + + var queue = Queue(capacity: 100) + + var runLoopCounter = 0 + + extension NSThread { + public var isMainThread: Bool { + return true + } + } + + public func CFRunLoopWakeUp(runLoop: CFRunLoopRef) { + } + + public func CFRunLoopStop(runLoop: CFRunLoopRef) { + runLoopCounter -= 1 + } + + public func CFRunLoopPerformBlock(runLoop: CFRunLoopRef, _ mode: String, _ action: () -> ()) { + queue.enqueue(action) + } + + public func CFRunLoopRun() { + runLoopCounter += 1 + let currentValueOfCounter = runLoopCounter + while let front = queue.dequeue() { + front() + if runLoopCounter < currentValueOfCounter - 1 { + fatalError("called stop twice") + } + + if runLoopCounter == currentValueOfCounter - 1 { + break + } + } + } + + public func CFRunLoopGetCurrent() -> CFRunLoopRef { + return 0 + } + + // MARK: Atomic, just something that works for single thread case + + #if TRACE_RESOURCES + public typealias AtomicInt = Int64 + #else + typealias AtomicInt = Int64 + #endif + + func AtomicIncrement(increment: UnsafeMutablePointer) -> AtomicInt { + increment.memory = increment.memory + 1 + return increment.memory + } + + func AtomicDecrement(increment: UnsafeMutablePointer) -> AtomicInt { + increment.memory = increment.memory - 1 + return increment.memory + } + + func AtomicCompareAndSwap(l: AtomicInt, _ r: AtomicInt, _ target: UnsafeMutablePointer) -> Bool { + //return __sync_val_compare_and_swap(target, l, r) + if target.memory == l { + target.memory = r + return true + } + + return false + } + + extension NSThread { + static func setThreadLocalStorageValue(value: T?, forKey key: String) { + let currentThread = NSThread.currentThread() + var threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + + currentThread.threadDictionary = threadDictionary + } + + static func getThreadLocalStorageValueForKey(key: String) -> T? { + let currentThread = NSThread.currentThread() + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + + // + + // MARK: objc mock + + public func objc_sync_enter(lock: AnyObject) { + } + + public func objc_sync_exit(lock: AnyObject) { + + } + + + // MARK: libdispatch + + public typealias dispatch_time_t = Int + public typealias dispatch_source_t = Int + public typealias dispatch_source_type_t = Int + public typealias dispatch_queue_t = Int + public typealias dispatch_object_t = Int + public typealias dispatch_block_t = () -> () + public typealias dispatch_queue_attr_t = Int + public typealias qos_class_t = Int + + public let DISPATCH_QUEUE_SERIAL = 0 + + public let DISPATCH_QUEUE_PRIORITY_HIGH = 1 + public let DISPATCH_QUEUE_PRIORITY_DEFAULT = 2 + public let DISPATCH_QUEUE_PRIORITY_LOW = 3 + + public let QOS_CLASS_USER_INTERACTIVE = 0 + public let QOS_CLASS_USER_INITIATED = 1 + public let QOS_CLASS_DEFAULT = 2 + public let QOS_CLASS_UTILITY = 3 + public let QOS_CLASS_BACKGROUND = 4 + + public let DISPATCH_SOURCE_TYPE_TIMER = 0 + public let DISPATCH_TIME_FOREVER = 1 as UInt64 + public let NSEC_PER_SEC = 1 + + public let DISPATCH_TIME_NOW = -1 + + public func dispatch_time(when: dispatch_time_t, _ delta: Int64) -> dispatch_time_t { + return when + Int(delta) + } + + public func dispatch_queue_create(label: UnsafePointer, _ attr: dispatch_queue_attr_t!) -> dispatch_queue_t! { + return 0 + } + + public func dispatch_set_target_queue(object: dispatch_object_t!, _ queue: dispatch_queue_t!) { + } + + public func dispatch_async(queue2: dispatch_queue_t, _ block: dispatch_block_t) { + queue.enqueue(block) + } + + public func dispatch_source_create(type: dispatch_source_type_t, _ handle: UInt, _ mask: UInt, _ queue: dispatch_queue_t!) -> dispatch_source_t! { + return 0 + } + + public func dispatch_source_set_timer(source: dispatch_source_t, _ start: dispatch_time_t, _ interval: UInt64, _ leeway: UInt64) { + + } + + public func dispatch_source_set_event_handler(source: dispatch_source_t, _ handler: dispatch_block_t!) { + queue.enqueue(handler) + } + + public func dispatch_resume(object: dispatch_object_t) { + } + + public func dispatch_source_cancel(source: dispatch_source_t) { + } + + public func dispatch_get_global_queue(identifier: Int, _ flags: UInt) -> dispatch_queue_t! { + return 0 + } + + public func dispatch_get_main_queue() -> dispatch_queue_t! { + return 0 + } + + // MARK: XCTest + + public class Expectation { + public func fulfill() { + } + } + + extension XCTestCase { + public func setUp() { + } + + public func tearDown() { + } + + public func expectationWithDescription(description: String) -> Expectation { + return Expectation() + } + + public func waitForExpectationsWithTimeout(time: NSTimeInterval, action: ErrorType? -> Void) { + } + } + +#endif diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 00000000000..8e33574e976 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,42 @@ +// +// Rx.swift +// Rx +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES +/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. +public var resourceCount: AtomicInt = 0 +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +@noreturn func abstractMethod() -> Void { + rxFatalError("Abstract method") +} + +@noreturn func rxFatalError(lastMessage: String) { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage) +} + +func incrementChecked(inout i: Int) throws -> Int { + if i == Int.max { + throw RxError.Overflow + } + let result = i + i += 1 + return result +} + +func decrementChecked(inout i: Int) throws -> Int { + if i == Int.min { + throw RxError.Overflow + } + let result = i + i -= 1 + return result +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 00000000000..6f5e5c3e648 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,37 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Creates mutable reference wrapper for any type. +*/ +class RxMutableBox : CustomDebugStringConvertible { + /** + Wrapped value + */ + var value : T + + /** + Creates reference wrapper for `value`. + + - parameter value: Value to wrap. + */ + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /** + - returns: Box description. + */ + var debugDescription: String { + return "MutatingBox(\(self.value))" + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 00000000000..b88d9cd0701 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,78 @@ +// +// SchedulerType.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Type that represents time interval in the context of RxSwift. +*/ +public typealias RxTimeInterval = NSTimeInterval + +/** +Type that represents absolute time in the context of RxSwift. +*/ +public typealias RxTime = NSDate + +/** +Represents an object that schedules units of work. +*/ +public protocol SchedulerType: ImmediateSchedulerType { + + /** + - returns: Current time. + */ + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(state: StateType, dueTime: RxTimeInterval, action: (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(state: State, dueTime: RxTimeInterval, action: (state: State, scheduler: AnyRecursiveScheduler) -> ()) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return AnonymousDisposable(scheduler.dispose) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 00000000000..7b8d8fec7a3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,147 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. + +This scheduler is suitable when some work needs to be performed in background. +*/ +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = NSTimeInterval + public typealias Time = NSDate + + private let _queue : dispatch_queue_t + + public var now : NSDate { + return NSDate() + } + + // leeway for scheduling timers + private var _leeway: Int64 = 0 + + /** + Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + + - parameter queue: Target dispatch queue. + */ + public init(queue: dispatch_queue_t) { + _queue = queue + } + + /** + Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + + - parameter globalConcurrentQueueQOS: Target global dispatch queue, by quality of service class. + */ + @available(iOS 8, OSX 10.10, *) + public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS) { + let priority = globalConcurrentQueueQOS.QOSClass + self.init(queue: dispatch_get_global_queue(priority, UInt(0))) + } + + + class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 { + return Int64(timeInterval * Double(NSEC_PER_SEC)) + } + + class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t { + return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval)) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(state: StateType, action: StateType -> Disposable) -> Disposable { + return self.scheduleInternal(state, action: action) + } + + func scheduleInternal(state: StateType, action: StateType -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + dispatch_async(_queue) { + if cancel.disposed { + return + } + + cancel.disposable = action(state) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue) + + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime) + + let compositeDisposable = CompositeDisposable() + + dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0) + dispatch_source_set_event_handler(timer, { + if compositeDisposable.disposed { + return + } + compositeDisposable.addDisposable(action(state)) + }) + dispatch_resume(timer) + + compositeDisposable.addDisposable(AnonymousDisposable { + dispatch_source_cancel(timer) + }) + + return compositeDisposable + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue) + + let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter) + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period) + + var timerState = state + + let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval) + + dispatch_source_set_timer(timer, initial, validDispatchInterval, 0) + let cancel = AnonymousDisposable { + dispatch_source_cancel(timer) + } + dispatch_source_set_event_handler(timer, { + if cancel.disposed { + return + } + timerState = action(timerState) + }) + dispatch_resume(timer) + + return cancel + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 00000000000..beac999bf51 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,90 @@ +// +// ConcurrentMainScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = NSTimeInterval + public typealias Time = NSDate + + private let _mainScheduler: MainScheduler + private let _mainQueue: dispatch_queue_t + + /** + - returns: Current time. + */ + public var now : NSDate { + return _mainScheduler.now + } + + private init(mainScheduler: MainScheduler) { + _mainQueue = dispatch_get_main_queue() + _mainScheduler = mainScheduler + } + + /** + Singleton instance of `ConcurrentMainScheduler` + */ + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + if NSThread.currentThread().isMainThread { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + dispatch_async(_mainQueue) { + if cancel.disposed { + return + } + + cancel.disposable = action(state) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { + return _mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { + return _mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 00000000000..b1c638847a1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,147 @@ +// +// CurrentThreadScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if os(Linux) + let CurrentThreadSchedulerKeyInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" + let CurrentThreadSchedulerQueueKeyInstance = "RxSwift.CurrentThreadScheduler.Queue" + + typealias CurrentThreadSchedulerValue = NSString + let CurrentThreadSchedulerValueInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" as NSString +#else + let CurrentThreadSchedulerKeyInstance = CurrentThreadSchedulerKey() + let CurrentThreadSchedulerQueueKeyInstance = CurrentThreadSchedulerQueueKey() + + typealias CurrentThreadSchedulerValue = CurrentThreadSchedulerKey + let CurrentThreadSchedulerValueInstance = CurrentThreadSchedulerKeyInstance + + class CurrentThreadSchedulerKey : NSObject, NSCopying { + override func isEqual(object: AnyObject?) -> Bool { + return object === CurrentThreadSchedulerKeyInstance + } + + override var hash: Int { return -904739208 } + + override func copy() -> AnyObject { + return CurrentThreadSchedulerKeyInstance + } + + func copyWithZone(zone: NSZone) -> AnyObject { + return CurrentThreadSchedulerKeyInstance + } + } + + class CurrentThreadSchedulerQueueKey : NSObject, NSCopying { + override func isEqual(object: AnyObject?) -> Bool { + return object === CurrentThreadSchedulerQueueKeyInstance + } + + override var hash: Int { return -904739207 } + + override func copy() -> AnyObject { + return CurrentThreadSchedulerQueueKeyInstance + } + + func copyWithZone(zone: NSZone) -> AnyObject { + return CurrentThreadSchedulerQueueKeyInstance + } + } +#endif + +/** +Represents an object that schedules units of work on the current thread. + +This is the default scheduler for operators that generate elements. + +This scheduler is also sometimes called `trampoline scheduler`. +*/ +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /** + The singleton instance of the current thread scheduler. + */ + public static let instance = CurrentThreadScheduler() + + static var queue : ScheduleQueue? { + get { + return NSThread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKeyInstance) + } + set { + NSThread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKeyInstance) + } + } + + /** + Gets a value that indicates whether the caller must call a `schedule` method. + */ + public static private(set) var isScheduleRequired: Bool { + get { + let value: CurrentThreadSchedulerValue? = NSThread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerKeyInstance) + return value == nil + } + set(isScheduleRequired) { + NSThread.setThreadLocalStorageValue(isScheduleRequired ? nil : CurrentThreadSchedulerValueInstance, forKey: CurrentThreadSchedulerKeyInstance) + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.disposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + // In Xcode 7.3, `return scheduledItem` causes segmentation fault 11 on release build. + // To workaround this compiler issue, returns AnonymousDisposable that disposes scheduledItem. + return AnonymousDisposable(scheduledItem.dispose) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift new file mode 100644 index 00000000000..96154807d75 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift @@ -0,0 +1,54 @@ +// +// DispatchQueueSchedulerQOS.swift +// RxSwift +// +// Created by John C. "Hsoi" Daub on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Identifies one of the global concurrent dispatch queues with specified quality of service class. +*/ +public enum DispatchQueueSchedulerQOS { + + /** + Identifies global dispatch queue with `QOS_CLASS_USER_INTERACTIVE` + */ + case UserInteractive + + /** + Identifies global dispatch queue with `QOS_CLASS_USER_INITIATED` + */ + case UserInitiated + + /** + Identifies global dispatch queue with `QOS_CLASS_DEFAULT` + */ + case Default + + /** + Identifies global dispatch queue with `QOS_CLASS_UTILITY` + */ + case Utility + + /** + Identifies global dispatch queue with `QOS_CLASS_BACKGROUND` + */ + case Background +} + + +@available(iOS 8, OSX 10.10, *) +extension DispatchQueueSchedulerQOS { + var QOSClass: qos_class_t { + switch self { + case .UserInteractive: return QOS_CLASS_USER_INTERACTIVE + case .UserInitiated: return QOS_CLASS_USER_INITIATED + case .Default: return QOS_CLASS_DEFAULT + case .Utility: return QOS_CLASS_UTILITY + case .Background: return QOS_CLASS_BACKGROUND + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 00000000000..949748e15ed --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,25 @@ +// +// HistoricalScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Provides a virtual time scheduler that uses `NSDate` for absolute time and `NSTimeInterval` for relative time. +*/ +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = NSDate(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 00000000000..8384beb4319 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,83 @@ +// +// HistoricalSchedulerTimeConverter.swift +// Rx +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Converts historial virtual time into real time. + + Since historical virtual time is also measured in `NSDate`, this converter is identity function. + */ +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /** + Virtual time unit used that represents ticks of virtual clock. + */ + public typealias VirtualTimeUnit = RxTime + + /** + Virtual time unit used to represent differences of virtual times. + */ + public typealias VirtualTimeIntervalUnit = RxTimeInterval + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime { + return virtualTime + } + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit { + return time + } + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval { + return virtualTimeInterval + } + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit { + return timeInterval + } + + /** + Offsets `NSDate` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + return time.dateByAddingTimeInterval(offset) + } + + /** + Compares two `NSDate`s. + */ + public func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs) { + case .OrderedAscending: + return .LessThan + case .OrderedSame: + return .Equal + case .OrderedDescending: + return .GreaterThan + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift new file mode 100644 index 00000000000..4371c5ec03b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift @@ -0,0 +1,39 @@ +// +// ImmediateScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an object that schedules units of work to run immediately on the current thread. +*/ +private class ImmediateScheduler : ImmediateSchedulerType { + + private let _asyncLock = AsyncLock() + + /** + Schedules an action to be executed immediately. + + In case `schedule` is called recursively from inside of `action` callback, scheduled `action` will be enqueued + and executed after current `action`. (`AsyncLock` behavior) + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + let disposable = SingleAssignmentDisposable() + _asyncLock.invoke(AnonymousInvocable { + if disposable.disposed { + return + } + disposable.disposable = action(state) + }) + + return disposable + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift new file mode 100644 index 00000000000..8525db45845 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift @@ -0,0 +1,21 @@ +// +// AnonymousInvocable.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct AnonymousInvocable : InvocableType { + private let _action: () -> () + + init(_ action: () -> ()) { + _action = action + } + + func invoke() { + _action() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 00000000000..1a4e3aa44e0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,24 @@ +// +// InvocableScheduledItem.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct InvocableScheduledItem : InvocableType { + + let _invocable: I + let _state: I.Value + + init(invocable: I, state: I.Value) { + _invocable = invocable + _state = state + } + + func invoke() { + _invocable.invoke(_state) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 00000000000..1632e71dada --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,19 @@ +// +// InvocableType.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(value: Value) +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 00000000000..d4c9a2c65b5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,37 @@ +// +// ScheduledItem.swift +// Rx +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = T -> Disposable + + private let _action: Action + private let _state: T + + private let _disposable = SingleAssignmentDisposable() + + var disposed: Bool { + return _disposable.disposed + } + + init(action: Action, state: T) { + _action = action + _state = state + } + + func invoke() { + _disposable.disposable = _action(_state) + } + + func dispose() { + _disposable.dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 00000000000..2a1eca272da --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,15 @@ +// +// ScheduledItemType.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 00000000000..ed109df7447 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,73 @@ +// +// MainScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let _mainQueue: dispatch_queue_t + + var numberEnqueued: AtomicInt = 0 + + private init() { + _mainQueue = dispatch_get_main_queue() + super.init(serialQueue: _mainQueue) + } + + /** + Singleton instance of `MainScheduler` + */ + public static let instance = MainScheduler() + + /** + Singleton instance of `MainScheduler` that always schedules work asynchronously + and doesn't perform optimizations for calls scheduled from main thread. + */ + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: dispatch_get_main_queue()) + + /** + In case this method is called on a background thread it will throw an exception. + */ + public class func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !NSThread.currentThread().isMainThread { + rxFatalError(errorMessage ?? "Executing on backgound thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + override func scheduleInternal(state: StateType, action: StateType -> Disposable) -> Disposable { + let currentNumberEnqueued = AtomicIncrement(&numberEnqueued) + + if NSThread.currentThread().isMainThread && currentNumberEnqueued == 1 { + let disposable = action(state) + AtomicDecrement(&numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + dispatch_async(_mainQueue) { + if !cancel.disposed { + action(state) + } + + AtomicDecrement(&self.numberEnqueued) + } + + return cancel + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 00000000000..8cfba8cafb5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,57 @@ +// +// OperationQueueScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `NSOperationQueue`. + +This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +*/ +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: NSOperationQueue + + /** + Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + + - parameter operationQueue: Operation queue targeted to perform work on. + */ + public init(operationQueue: NSOperationQueue) { + self.operationQueue = operationQueue + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + + let compositeDisposable = CompositeDisposable() + + weak var compositeDisposableWeak = compositeDisposable + + let operation = NSBlockOperation { + if compositeDisposableWeak?.disposed ?? false { + return + } + + let disposable = action(state) + compositeDisposableWeak?.addDisposable(disposable) + } + + self.operationQueue.addOperation(operation) + + compositeDisposable.addDisposable(AnonymousDisposable(operation.cancel)) + + return compositeDisposable + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 00000000000..dac4360cc81 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,193 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Type erased recursive scheduler. +*/ +class AnyRecursiveScheduler { + typealias Action = (state: State, scheduler: AnyRecursiveScheduler) -> Void + + private let _lock = NSRecursiveLock() + + // state + private let _group = CompositeDisposable() + + private var _scheduler: SchedulerType + private var _action: Action? + + init(scheduler: SchedulerType, action: Action) { + _action = action + _scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(state: State, dueTime: RxTimeInterval) { + + var isAdded = false + var isDone = false + + var removeKey: CompositeDisposable.DisposeKey? = nil + let d = _scheduler.scheduleRelative(state, dueTime: dueTime) { (state) -> Disposable in + // best effort + if self._group.disposed { + return NopDisposable.instance + } + + let action = self._lock.calculateLocked { () -> Action? in + if isAdded { + self._group.removeDisposable(removeKey!) + } + else { + isDone = true + } + + return self._action + } + + if let action = action { + action(state: state, scheduler: self) + } + + return NopDisposable.instance + } + + _lock.performLocked { + if !isDone { + removeKey = _group.addDisposable(d) + isAdded = true + } + } + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + */ + func schedule(state: State) { + + var isAdded = false + var isDone = false + + var removeKey: CompositeDisposable.DisposeKey? = nil + let d = _scheduler.schedule(state) { (state) -> Disposable in + // best effort + if self._group.disposed { + return NopDisposable.instance + } + + let action = self._lock.calculateLocked { () -> Action? in + if isAdded { + self._group.removeDisposable(removeKey!) + } + else { + isDone = true + } + + return self._action + } + + if let action = action { + action(state: state, scheduler: self) + } + + return NopDisposable.instance + } + + _lock.performLocked { + if !isDone { + removeKey = _group.addDisposable(d) + isAdded = true + } + } + } + + func dispose() { + _lock.performLocked { + _action = nil + } + _group.dispose() + } +} + +/** +Type erased recursive scheduler. +*/ +class RecursiveImmediateScheduler { + typealias Action = (state: State, recurse: State -> Void) -> Void + + private var _lock = SpinLock() + private let _group = CompositeDisposable() + + private var _action: Action? + private let _scheduler: ImmediateSchedulerType + + init(action: Action, scheduler: ImmediateSchedulerType) { + _action = action + _scheduler = scheduler + } + + // immediate scheduling + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + */ + func schedule(state: State) { + + var isAdded = false + var isDone = false + + var removeKey: CompositeDisposable.DisposeKey? = nil + let d = _scheduler.schedule(state) { (state) -> Disposable in + // best effort + if self._group.disposed { + return NopDisposable.instance + } + + let action = self._lock.calculateLocked { () -> Action? in + if isAdded { + self._group.removeDisposable(removeKey!) + } + else { + isDone = true + } + + return self._action + } + + if let action = action { + action(state: state, recurse: self.schedule) + } + + return NopDisposable.instance + } + + _lock.performLocked { + if !isDone { + removeKey = _group.addDisposable(d) + isAdded = true + } + } + } + + func dispose() { + _lock.performLocked { + _action = nil + } + _group.dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 00000000000..a7523a815d0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,63 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +enum SchedulePeriodicRecursiveCommand { + case Tick + case DispatchStart +} + +class SchedulePeriodicRecursive { + typealias RecursiveAction = State -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let _scheduler: SchedulerType + private let _startAfter: RxTimeInterval + private let _period: RxTimeInterval + private let _action: RecursiveAction + + private var _state: State + private var _pendingTickCount: AtomicInt = 0 + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: RecursiveAction, state: State) { + _scheduler = scheduler + _startAfter = startAfter + _period = period + _action = action + _state = state + } + + func start() -> Disposable { + return _scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.Tick, dueTime: _startAfter, action: self.tick) + } + + func tick(command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) -> Void { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .Tick: + scheduler.schedule(.Tick, dueTime: _period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. + // Else work will be scheduled after previous enqueued work completes. + if AtomicIncrement(&_pendingTickCount) == 1 { + self.tick(.DispatchStart, scheduler: scheduler) + } + + case .DispatchStart: + _state = _action(_state) + // Start work and schedule check is this last batch of work + if AtomicDecrement(&_pendingTickCount) > 0 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.DispatchStart) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 00000000000..ad2e31537fc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,184 @@ +// +// SerialDispatchQueueScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = NSTimeInterval + public typealias Time = NSDate + + private let _serialQueue : dispatch_queue_t + + /** + - returns: Current time. + */ + public var now : NSDate { + return NSDate() + } + + // leeway for scheduling timers + private var _leeway: Int64 = 0 + + init(serialQueue: dispatch_queue_t) { + _serialQueue = serialQueue + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((dispatch_queue_t) -> Void)? = nil) { + let queue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + */ + public convenience init(queue: dispatch_queue_t, internalSerialQueueName: String) { + let serialQueue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) + dispatch_set_target_queue(serialQueue, queue) + self.init(serialQueue: serialQueue) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. + + - parameter globalConcurrentQueueQOS: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + */ + @available(iOS 8, OSX 10.10, *) + public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial") { + let priority = globalConcurrentQueueQOS.QOSClass + self.init(queue: dispatch_get_global_queue(priority, UInt(0)), internalSerialQueueName: internalSerialQueueName) + } + + class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 { + return Int64(timeInterval * Double(NSEC_PER_SEC)) + } + + class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t { + return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval)) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + return self.scheduleInternal(state, action: action) + } + + func scheduleInternal(state: StateType, action: (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + dispatch_async(_serialQueue) { + if cancel.disposed { + return + } + + + cancel.disposable = action(state) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _serialQueue) + + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime) + + let compositeDisposable = CompositeDisposable() + + dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0) + dispatch_source_set_event_handler(timer, { + if compositeDisposable.disposed { + return + } + compositeDisposable.addDisposable(action(state)) + }) + dispatch_resume(timer) + + compositeDisposable.addDisposable(AnonymousDisposable { + dispatch_source_cancel(timer) + }) + + return compositeDisposable + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _serialQueue) + + let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter) + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period) + + var timerState = state + + let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval) + + dispatch_source_set_timer(timer, initial, validDispatchInterval, 0) + let cancel = AnonymousDisposable { + dispatch_source_cancel(timer) + } + dispatch_source_set_event_handler(timer, { + if cancel.disposed { + return + } + timerState = action(timerState) + }) + dispatch_resume(timer) + + return cancel + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 00000000000..61a58ca62f7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,115 @@ +// +// VirtualTimeConverterType.swift +// Rx +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Parametrization for virtual time used by `VirtualTimeScheduler`s. +*/ +public protocol VirtualTimeConverterType { + /** + Virtual time unit used that represents ticks of virtual clock. + */ + associatedtype VirtualTimeUnit + + /** + Virtual time unit used to represent differences of virtual times. + */ + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `NSDate`. + - returns: `NSDate` corresponding to virtual time. + */ + func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `NSDate` to convert to virtual time. + - returns: Virtual time corresponding to `NSDate`. + */ + func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is aditional abstraction because `NSDate` is unfortunately not comparable. + Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is aditional abstraction because `NSDate` is unfortunately not comparable. + Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /** + lhs < rhs. + */ + case LessThan + /** + lhs == rhs. + */ + case Equal + /** + lhs > rhs. + */ + case GreaterThan +} + +extension VirtualTimeComparison { + /** + lhs < rhs. + */ + var lessThen: Bool { + return self == .LessThan + } + + /** + lhs > rhs + */ + var greaterThan: Bool { + return self == .GreaterThan + } + + /** + lhs == rhs + */ + var equal: Bool { + return self == .Equal + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 00000000000..d365bd0df0f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,292 @@ +// +// VirtualTimeScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Base class for virtual time schedulers using a priority queue for scheduled items. +*/ +public class VirtualTimeScheduler + : SchedulerType + , CustomDebugStringConvertible { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var _running : Bool + + private var _clock: VirtualTime + + private var _schedulerQueue : PriorityQueue> + private var _converter: Converter + + private var _nextId = 0 + + /** + - returns: Current time. + */ + public var now: RxTime { + return _converter.convertFromVirtualTime(clock) + } + + /** + - returns: Scheduler's absolute time clock value. + */ + public var clock: VirtualTime { + return _clock + } + + /** + Creates a new virtual time scheduler. + + - parameter initialClock: Initial value for the clock. + */ + public init(initialClock: VirtualTime, converter: Converter) { + _clock = initialClock + _running = false + _converter = converter + _schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .LessThan: + return true + case .Equal: + return $0.id < $1.id + case .GreaterThan: + return false + } + }) + #if TRACE_RESOURCES + AtomicIncrement(&resourceCount) + #endif + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: StateType -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: 0.0) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(state: StateType, dueTime: RxTimeInterval, action: StateType -> Disposable) -> Disposable { + let time = self.now.dateByAddingTimeInterval(dueTime) + let absoluteTime = _converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(state: StateType, dueTime: VirtualTimeInterval, action: StateType -> Disposable) -> Disposable { + let time = _converter.offsetVirtualTime(time: self.clock, offset: dueTime) + return scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(state: StateType, time: Converter.VirtualTimeUnit, action: StateType -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + let dispose = action(state) + return dispose + }, time: time, id: _nextId) + + _nextId += 1 + + _schedulerQueue.enqueue(item) + + compositeDisposable.addDisposable(item) + + return compositeDisposable + } + + /** + Adjusts time of scheduling before adding item to schedule queue. + */ + public func adjustScheduledTime(time: Converter.VirtualTimeUnit) -> Converter.VirtualTimeUnit { + return time + } + + /** + Starts the virtual time scheduler. + */ + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if _running { + return + } + + _running = true + repeat { + guard let next = findNext() else { + break + } + + if _converter.compareVirtualTime(next.time, self.clock).greaterThan { + _clock = next.time + } + + next.invoke() + _schedulerQueue.remove(next) + } while _running + + _running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = _schedulerQueue.peek() { + if front.disposed { + _schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /** + Advances the scheduler's clock to the specified time, running all work till that point. + + - parameter virtualTime: Absolute time to advance the scheduler's clock to. + */ + public func advanceTo(virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if _running { + fatalError("Scheduler is already running") + } + + _running = true + repeat { + guard let next = findNext() else { + break + } + + if _converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if _converter.compareVirtualTime(next.time, self.clock).greaterThan { + _clock = next.time + } + + next.invoke() + _schedulerQueue.remove(next) + } while _running + + _clock = virtualTime + _running = false + } + + /** + Advances the scheduler's clock by the specified relative time. + */ + public func sleep(virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = _converter.offsetVirtualTime(time: clock, offset: virtualInterval) + if _converter.compareVirtualTime(sleepTo, clock).lessThen { + fatalError("Can't sleep to past.") + } + + _clock = sleepTo + } + + /** + Stops the virtual time scheduler. + */ + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + _running = false + } + + #if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler { + /** + A textual representation of `self`, suitable for debugging. + */ + public var debugDescription: String { + return self._schedulerQueue.debugDescription + } +} + +class VirtualSchedulerItem
    Version: 1.0.0
    +
    BasePath:/v2
    Apache 2.0
    http://www.apache.org/licenses/LICENSE-2.0.html

    Access

    - +
      +
    1. APIKey KeyParamName:api_key KeyInQuery:false KeyInHeader:true
    2. +
    3. OAuth AuthorizationUrl:http://petstore.swagger.io/api/oauth/dialogTokenUrl:
    4. +

    Methods

    [ Jump to Models ] -

    Table of Contents

    +

    Table of Contents

    -
      +

      Pet

      + +

      Store

      + +

      User

      +
    + +

    Pet

    Up @@ -259,6 +269,7 @@

    Produces

    Responses

    405

    Invalid input +





    @@ -468,10 +575,13 @@

    Produces

    Responses

    400

    Invalid ID supplied +

    404

    Pet not found +

    405

    Validation exception +



    +

    Store

    Up @@ -610,8 +730,10 @@

    Produces

    Responses

    400

    Invalid ID supplied +

    404

    Order not found +




    +

    User

    Up @@ -770,6 +944,7 @@

    Produces

    Responses

    0

    successful operation +








    @@ -1051,7 +1268,7 @@

    404

    Models

    [ Jump to Methods ] -

    Table of Contents

    +

    Table of Contents

    1. ApiResponse
    2. Category
    3. @@ -1062,64 +1279,70 @@

      Table of Contents

    -

    ApiResponse Up

    +

    ApiResponse - An uploaded response Up

    +
    Describes the result of uploading an image resource
    -
    code (optional)
    Integer
    -
    type (optional)
    String
    -
    message (optional)
    String
    +
    code (optional)
    Integer format: int32
    +
    type (optional)
    +
    message (optional)
    -

    Category Up

    +

    Category - Pet catehgry Up

    +
    A category for a pet
    -
    id (optional)
    Long
    -
    name (optional)
    String
    +
    id (optional)
    Long format: int64
    +
    name (optional)
    -

    Order Up

    +

    Order - Pet Order Up

    +
    An order for a pets from the pet store
    -
    id (optional)
    Long
    -
    petId (optional)
    Long
    -
    quantity (optional)
    Integer
    -
    shipDate (optional)
    Date
    -
    status (optional)
    String Order Status
    +
    id (optional)
    Long format: int64
    +
    petId (optional)
    Long format: int64
    +
    quantity (optional)
    Integer format: int32
    +
    shipDate (optional)
    Date format: date-time
    +
    status (optional)
    String Order Status
    Enum:
    placed
    approved
    delivered
    -
    complete (optional)
    Boolean
    +
    complete (optional)
    -

    Pet Up

    +

    Pet - a Pet Up

    +
    A pet for sale in the pet store
    -
    id (optional)
    Long
    -
    category (optional)
    Category
    -
    name
    String
    -
    photoUrls
    array[String]
    -
    tags (optional)
    array[Tag]
    -
    status (optional)
    String pet status in the store
    +
    id (optional)
    Long format: int64
    +
    category (optional)
    +
    name
    +
    photoUrls
    +
    tags (optional)
    +
    status (optional)
    String pet status in the store
    Enum:
    available
    pending
    sold
    -

    Tag Up

    +

    Tag - Pet Tag Up

    +
    A tag for a pet
    -
    id (optional)
    Long
    -
    name (optional)
    String
    +
    id (optional)
    Long format: int64
    +
    name (optional)
    -

    User Up

    +

    User - a User Up

    +
    A User who is purchasing from the pet store
    -
    id (optional)
    Long
    -
    username (optional)
    String
    -
    firstName (optional)
    String
    -
    lastName (optional)
    String
    -
    email (optional)
    String
    -
    password (optional)
    String
    -
    phone (optional)
    String
    -
    userStatus (optional)
    Integer User Status
    +
    id (optional)
    Long format: int64
    +
    username (optional)
    +
    firstName (optional)
    +
    lastName (optional)
    +
    email (optional)
    +
    password (optional)
    +
    phone (optional)
    +
    userStatus (optional)
    Integer User Status format: int32
    diff --git a/samples/html2/.swagger-codegen-ignore b/samples/html2/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/html2/.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/html2/LICENSE b/samples/html2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/html2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/html2/index.html b/samples/html2/index.html new file mode 100644 index 00000000000..38c4970ed5e --- /dev/null +++ b/samples/html2/index.html @@ -0,0 +1,10286 @@ + + + + + Swagger Petstore + + + + + + + + + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +

    Swagger Petstore

    +
    +
    +
    + +
    + + +
    +

    Pet

    + + + + + + + +
    + +
    +
    +

    addPet

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /pet
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/pet"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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 = ; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        Pet body = ; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +Pet *body = ; // Pet object that needs to be added to the store
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Add a new pet to the store
    +[apiInstance addPetWith:body
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var body = ; // {Pet} Pet object that needs to be added to the store
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.addPet(body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$body = ; // Pet | Pet object that needs to be added to the store
    +
    +try {
    +    $api_instance->addPet($body);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 405 - Invalid input

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    deletePet

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /pet/{petId}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X delete "http://petstore.swagger.io/v2/pet/{petId}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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 = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        Long petId = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +Long *petId = 789; // Pet id to delete
    +String *apiKey = apiKey_example; //  (optional)
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Deletes a pet
    +[apiInstance deletePetWith:petId
    +    apiKey:apiKey
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var petId = 789; // {Long} Pet id to delete
    +
    +var opts = { 
    +  'apiKey': apiKey_example // {String} 
    +};
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.deletePet(petId, opts, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$petId = 789; // Long | Pet id to delete
    +$apiKey = apiKey_example; // String | 
    +
    +try {
    +    $api_instance->deletePet($petId, $apiKey);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    petId* + + + +
    +
    + +
    Header parameters
    + + + + + + + + + + + +
    NameDescription
    apiKey + + + +
    +
    + + + + +

    Responses

    + +

    Status: 400 - Invalid pet value

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    findPetsByStatus

    +
    +
    + +
    +
    + +

    +

    Multiple status values can be provided with comma separated strings

    +

    +
    + +
    /pet/findByStatus
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get "http://petstore.swagger.io/v2/pet/findByStatus?status="
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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();
    +        array[String] status = ; // array[String] | Status values that need to be considered for filter
    +        try {
    +            array[Pet] result = apiInstance.findPetsByStatus(status);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PetApi#findPetsByStatus");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        array[String] status = ; // array[String] | Status values that need to be considered for filter
    +        try {
    +            array[Pet] result = apiInstance.findPetsByStatus(status);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PetApi#findPetsByStatus");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +array[String] *status = ; // Status values that need to be considered for filter
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Finds Pets by status
    +[apiInstance findPetsByStatusWith:status
    +              completionHandler: ^(array[Pet] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var status = ; // {array[String]} Status values that need to be considered for filter
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.findPetsByStatus(status, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 array[String](); // array[String] | Status values that need to be considered for filter
    +
    +            try
    +            {
    +                // Finds Pets by status
    +                array[Pet] result = apiInstance.findPetsByStatus(status);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling PetApi.findPetsByStatus: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$status = ; // array[String] | Status values that need to be considered for filter
    +
    +try {
    +    $result = $api_instance->findPetsByStatus($status);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + + +
    Query parameters
    + + + + + + + + + + +
    NameDescription
    status* + + + +
    +
    + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid status value

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    findPetsByTags

    +
    +
    + +
    +
    + +

    +

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

    +

    +
    + +
    /pet/findByTags
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get "http://petstore.swagger.io/v2/pet/findByTags?tags="
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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();
    +        array[String] tags = ; // array[String] | Tags to filter by
    +        try {
    +            array[Pet] result = apiInstance.findPetsByTags(tags);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PetApi#findPetsByTags");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        array[String] tags = ; // array[String] | Tags to filter by
    +        try {
    +            array[Pet] result = apiInstance.findPetsByTags(tags);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PetApi#findPetsByTags");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +array[String] *tags = ; // Tags to filter by
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Finds Pets by tags
    +[apiInstance findPetsByTagsWith:tags
    +              completionHandler: ^(array[Pet] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var tags = ; // {array[String]} Tags to filter by
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.findPetsByTags(tags, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 array[String](); // array[String] | Tags to filter by
    +
    +            try
    +            {
    +                // Finds Pets by tags
    +                array[Pet] result = apiInstance.findPetsByTags(tags);
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling PetApi.findPetsByTags: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$tags = ; // array[String] | Tags to filter by
    +
    +try {
    +    $result = $api_instance->findPetsByTags($tags);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + + +
    Query parameters
    + + + + + + + + + + +
    NameDescription
    tags* + + + +
    +
    + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid tag value

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    getPetById

    +
    +
    + +
    +
    + +

    +

    Returns a single pet

    +

    +
    + +
    /pet/{petId}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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 = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        Long petId = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure API key authorization: (authentication scheme: api_key)
    +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
    +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
    +
    +
    +Long *petId = 789; // ID of pet to return
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Find pet by ID
    +[apiInstance getPetByIdWith:petId
    +              completionHandler: ^(Pet output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure API key authorization: api_key
    +var api_key = defaultClient.authentications['api_key'];
    +api_key.apiKey = "YOUR API KEY"
    +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
    +//api_key.apiKeyPrefix['api_key'] = "Token"
    +
    +var api = new .PetApi()
    +
    +var petId = 789; // {Long} ID of pet to return
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.getPetById(petId, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +namespace Example
    +{
    +    public class getPetByIdExample
    +    {
    +        public void main()
    +        {
    +            
    +            // Configure API key authorization: api_key
    +            Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
    +            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +            // Configuration.Default.ApiKeyPrefix.Add("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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setApiKey('api_key', 'YOUR_API_KEY');
    +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +// io.swagger.client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$petId = 789; // Long | ID of pet to return
    +
    +try {
    +    $result = $api_instance->getPetById($petId);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    petId* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid ID supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - Pet not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    updatePet

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /pet
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X put "http://petstore.swagger.io/v2/pet"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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 = ; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        Pet body = ; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +Pet *body = ; // Pet object that needs to be added to the store
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Update an existing pet
    +[apiInstance updatePetWith:body
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var body = ; // {Pet} Pet object that needs to be added to the store
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.updatePet(body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$body = ; // Pet | Pet object that needs to be added to the store
    +
    +try {
    +    $api_instance->updatePet($body);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 400 - Invalid ID supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - Pet not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 405 - Validation exception

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    updatePetWithForm

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /pet/{petId}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/pet/{petId}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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 = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        Long petId = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +Long *petId = 789; // ID of pet that needs to be updated
    +String *name = name_example; // Updated name of the pet (optional)
    +String *status = status_example; // Updated status of the pet (optional)
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// Updates a pet in the store with form data
    +[apiInstance updatePetWithFormWith:petId
    +    name:name
    +    status:status
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var petId = 789; // {Long} ID of pet that needs to be updated
    +
    +var opts = { 
    +  'name': name_example, // {String} Updated name of the pet
    +  'status': status_example // {String} Updated status of the pet
    +};
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.updatePetWithForm(petId, opts, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$petId = 789; // Long | 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($petId, $name, $status);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    petId* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 405 - Invalid input

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    uploadFile

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /pet/{petId}/uploadImage
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/pet/{petId}/uploadImage"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .PetApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        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 = 789; // Long | ID of pet to update
    +        String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
    +        file file = /path/to/file.txt; // file | file to upload
    +        try {
    +            ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PetApi#uploadFile");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .PetApi;
    +
    +public class PetApiExample {
    +
    +    public static void main(String[] args) {
    +        PetApi apiInstance = new PetApi();
    +        Long petId = 789; // Long | ID of pet to update
    +        String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
    +        file file = /path/to/file.txt; // file | file to upload
    +        try {
    +            ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file);
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling PetApi#uploadFile");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
    +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    +
    +
    +Long *petId = 789; // ID of pet to update
    +String *additionalMetadata = additionalMetadata_example; // Additional data to pass to server (optional)
    +file *file = /path/to/file.txt; // file to upload (optional)
    +
    +PetApi *apiInstance = [[PetApi alloc] init];
    +
    +// uploads an image
    +[apiInstance uploadFileWith:petId
    +    additionalMetadata:additionalMetadata
    +    file:file
    +              completionHandler: ^(ApiResponse output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure OAuth2 access token for authorization: petstore_auth
    +var petstore_auth = defaultClient.authentications['petstore_auth'];
    +petstore_auth.accessToken = "YOUR ACCESS TOKEN"
    +
    +var api = new .PetApi()
    +
    +var petId = 789; // {Long} ID of pet to update
    +
    +var opts = { 
    +  'additionalMetadata': additionalMetadata_example, // {String} Additional data to pass to server
    +  'file': /path/to/file.txt // {file} file to upload
    +};
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.uploadFile(petId, opts, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 file(); // file | 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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setAccessToken('YOUR_ACCESS_TOKEN');
    +
    +$api_instance = new io.swagger.client\Api\PetApi();
    +$petId = 789; // Long | ID of pet to update
    +$additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
    +$file = /path/to/file.txt; // file | file to upload
    +
    +try {
    +    $result = $api_instance->uploadFile($petId, $additionalMetadata, $file);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    petId* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + +
    + +
    +

    Store

    + + + + + + + +
    + +
    +
    +

    deleteOrder

    +
    +
    + +
    +
    + +

    +

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

    +

    +
    + +
    /store/order/{orderId}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X delete "http://petstore.swagger.io/v2/store/order/{orderId}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .StoreApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .StoreApi;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +String *orderId = orderId_example; // ID of the order that needs to be deleted
    +
    +StoreApi *apiInstance = [[StoreApi alloc] init];
    +
    +// Delete purchase order by ID
    +[apiInstance deleteOrderWith:orderId
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .StoreApi()
    +
    +var orderId = orderId_example; // {String} ID of the order that needs to be deleted
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.deleteOrder(orderId, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +deleteOrder($orderId);
    +} catch (Exception $e) {
    +    echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    orderId* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 400 - Invalid ID supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - Order not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    getInventory

    +
    +
    + +
    +
    + +

    +

    Returns a map of status codes to quantities

    +

    +
    + +
    /store/inventory
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .StoreApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        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['String', 'Integer'] result = apiInstance.getInventory();
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling StoreApi#getInventory");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .StoreApi;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        StoreApi apiInstance = new StoreApi();
    +        try {
    +            map['String', 'Integer'] result = apiInstance.getInventory();
    +            System.out.println(result);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling StoreApi#getInventory");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +Configuration *apiConfig = [Configuration sharedConfig];
    +
    +// Configure API key authorization: (authentication scheme: api_key)
    +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
    +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
    +
    +
    +
    +StoreApi *apiInstance = [[StoreApi alloc] init];
    +
    +// Returns pet inventories by status
    +[apiInstance getInventoryWithCompletionHandler: 
    +              ^(map['String', 'Integer'] output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +var defaultClient = .ApiClient.instance;
    +
    +// Configure API key authorization: api_key
    +var api_key = defaultClient.authentications['api_key'];
    +api_key.apiKey = "YOUR API KEY"
    +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
    +//api_key.apiKeyPrefix['api_key'] = "Token"
    +
    +var api = new .StoreApi()
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.getInventory(callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +namespace Example
    +{
    +    public class getInventoryExample
    +    {
    +        public void main()
    +        {
    +            
    +            // Configure API key authorization: api_key
    +            Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
    +            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +            // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer");
    +
    +            var apiInstance = new StoreApi();
    +
    +            try
    +            {
    +                // Returns pet inventories by status
    +                map['String', 'Integer'] result = apiInstance.getInventory();
    +                Debug.WriteLine(result);
    +            }
    +            catch (Exception e)
    +            {
    +                Debug.Print("Exception when calling StoreApi.getInventory: " + e.Message );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +setApiKey('api_key', 'YOUR_API_KEY');
    +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +// io.swagger.client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
    +
    +$api_instance = new io.swagger.client\Api\StoreApi();
    +
    +try {
    +    $result = $api_instance->getInventory();
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + + + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    getOrderById

    +
    +
    + +
    +
    + +

    +

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

    +

    +
    + +
    /store/order/{orderId}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get "http://petstore.swagger.io/v2/store/order/{orderId}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .StoreApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        StoreApi apiInstance = new StoreApi();
    +        Long orderId = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .StoreApi;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        StoreApi apiInstance = new StoreApi();
    +        Long orderId = 789; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +Long *orderId = 789; // ID of pet that needs to be fetched
    +
    +StoreApi *apiInstance = [[StoreApi alloc] init];
    +
    +// Find purchase order by ID
    +[apiInstance getOrderByIdWith:orderId
    +              completionHandler: ^(Order output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .StoreApi()
    +
    +var orderId = 789; // {Long} ID of pet that needs to be fetched
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.getOrderById(orderId, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +getOrderById($orderId);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    orderId* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid ID supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - Order not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    placeOrder

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /store/order
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/store/order"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .StoreApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        StoreApi apiInstance = new StoreApi();
    +        Order body = ; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .StoreApi;
    +
    +public class StoreApiExample {
    +
    +    public static void main(String[] args) {
    +        StoreApi apiInstance = new StoreApi();
    +        Order body = ; // 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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +Order *body = ; // order placed for purchasing the pet
    +
    +StoreApi *apiInstance = [[StoreApi alloc] init];
    +
    +// Place an order for a pet
    +[apiInstance placeOrderWith:body
    +              completionHandler: ^(Order output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .StoreApi()
    +
    +var body = ; // {Order} order placed for purchasing the pet
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.placeOrder(body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +placeOrder($body);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid Order

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + +
    + +
    +

    User

    + + + + + + + +
    + +
    +
    +

    createUser

    +
    +
    + +
    +
    + +

    +

    This can only be done by the logged in user.

    +

    +
    + +
    /user
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/user"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        UserApi apiInstance = new UserApi();
    +        User body = ; // User | Created user object
    +        try {
    +            apiInstance.createUser(body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#createUser");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        UserApi apiInstance = new UserApi();
    +        User body = ; // User | Created user object
    +        try {
    +            apiInstance.createUser(body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#createUser");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +User *body = ; // Created user object
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Create user
    +[apiInstance createUserWith:body
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var body = ; // {User} Created user object
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.createUser(body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +createUser($body);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 0 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    createUsersWithArrayInput

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /user/createWithArray
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/user/createWithArray"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        UserApi apiInstance = new UserApi();
    +        array[User] body = ; // array[User] | List of user object
    +        try {
    +            apiInstance.createUsersWithArrayInput(body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#createUsersWithArrayInput");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        UserApi apiInstance = new UserApi();
    +        array[User] body = ; // array[User] | List of user object
    +        try {
    +            apiInstance.createUsersWithArrayInput(body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#createUsersWithArrayInput");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +array[User] *body = ; // List of user object
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Creates list of users with given input array
    +[apiInstance createUsersWithArrayInputWith:body
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var body = ; // {array[User]} List of user object
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.createUsersWithArrayInput(body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +namespace Example
    +{
    +    public class createUsersWithArrayInputExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new UserApi();
    +            var body = new array[User](); // array[User] | 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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +createUsersWithArrayInput($body);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 0 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    createUsersWithListInput

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /user/createWithList
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X post "http://petstore.swagger.io/v2/user/createWithList"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        UserApi apiInstance = new UserApi();
    +        array[User] body = ; // array[User] | List of user object
    +        try {
    +            apiInstance.createUsersWithListInput(body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#createUsersWithListInput");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        UserApi apiInstance = new UserApi();
    +        array[User] body = ; // array[User] | List of user object
    +        try {
    +            apiInstance.createUsersWithListInput(body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#createUsersWithListInput");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +array[User] *body = ; // List of user object
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Creates list of users with given input array
    +[apiInstance createUsersWithListInputWith:body
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var body = ; // {array[User]} List of user object
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.createUsersWithListInput(body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +namespace Example
    +{
    +    public class createUsersWithListInputExample
    +    {
    +        public void main()
    +        {
    +            
    +            var apiInstance = new UserApi();
    +            var body = new array[User](); // array[User] | 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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +createUsersWithListInput($body);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 0 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    deleteUser

    +
    +
    + +
    +
    + +

    +

    This can only be done by the logged in user.

    +

    +
    + +
    /user/{username}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X delete "http://petstore.swagger.io/v2/user/{username}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +String *username = username_example; // The name that needs to be deleted
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Delete user
    +[apiInstance deleteUserWith:username
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var username = username_example; // {String} The name that needs to be deleted
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.deleteUser(username, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +deleteUser($username);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    username* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 400 - Invalid username supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - User not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    getUserByName

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /user/{username}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get "http://petstore.swagger.io/v2/user/{username}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +String *username = username_example; // The name that needs to be fetched. Use user1 for testing. 
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Get user by user name
    +[apiInstance getUserByNameWith:username
    +              completionHandler: ^(User output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var username = username_example; // {String} The name that needs to be fetched. Use user1 for testing. 
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.getUserByName(username, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +getUserByName($username);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    username* + + + +
    +
    + + + + + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid username supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - User not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    loginUser

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /user/login
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get "http://petstore.swagger.io/v2/user/login?username=&password="
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        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();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +String *username = username_example; // The user name for login
    +String *password = password_example; // The password for login in clear text
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Logs user into the system
    +[apiInstance loginUserWith:username
    +    password:password
    +              completionHandler: ^('String' output, NSError* error) {
    +                            if (output) {
    +                                NSLog(@"%@", output);
    +                            }
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var username = username_example; // {String} The user name for login
    +
    +var password = password_example; // {String} The password for login in clear text
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully. Returned data: ' + data);
    +  }
    +};
    +api.loginUser(username, password, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +loginUser($username, $password);
    +    print_r($result);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + + +
    Query parameters
    + + + + + + + + + + + + + + +
    NameDescription
    username* + + + +
    +
    password* + + + +
    +
    + +

    Responses

    + +

    Status: 200 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 400 - Invalid username/password supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    logoutUser

    +
    +
    + +
    +
    + +

    +

    +

    +
    + +
    /user/logout
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X get "http://petstore.swagger.io/v2/user/logout"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        UserApi apiInstance = new UserApi();
    +        try {
    +            apiInstance.logoutUser();
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#logoutUser");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        UserApi apiInstance = new UserApi();
    +        try {
    +            apiInstance.logoutUser();
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#logoutUser");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Logs out current logged in user session
    +[apiInstance logoutUserWithCompletionHandler: 
    +              ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.logoutUser(callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +logoutUser();
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + + + + + + +

    Responses

    + +

    Status: 0 - successful operation

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    + +
    +
    +

    updateUser

    +
    +
    + +
    +
    + +

    +

    This can only be done by the logged in user.

    +

    +
    + +
    /user/{username}
    + +

    +

    Usage and SDK Samples

    +

    + + + +
    +
    +
    
    +curl -X put "http://petstore.swagger.io/v2/user/{username}"
    +
    +
    +
    +
    + +
    +
    
    +import io.swagger.client.*;
    +import io.swagger.client.auth.*;
    +import io.swagger.client.model.*;
    +import .UserApi;
    +
    +import java.io.File;
    +import java.util.*;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        
    +        UserApi apiInstance = new UserApi();
    +        String username = username_example; // String | name that need to be deleted
    +        User body = ; // User | Updated user object
    +        try {
    +            apiInstance.updateUser(username, body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#updateUser");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + +
    +
    
    +import .UserApi;
    +
    +public class UserApiExample {
    +
    +    public static void main(String[] args) {
    +        UserApi apiInstance = new UserApi();
    +        String username = username_example; // String | name that need to be deleted
    +        User body = ; // User | Updated user object
    +        try {
    +            apiInstance.updateUser(username, body);
    +        } catch (ApiException e) {
    +            System.err.println("Exception when calling UserApi#updateUser");
    +            e.printStackTrace();
    +        }
    +    }
    +}
    +
    +                                                  
    +
    + + + + +
    +
    
    +
    +String *username = username_example; // name that need to be deleted
    +User *body = ; // Updated user object
    +
    +UserApi *apiInstance = [[UserApi alloc] init];
    +
    +// Updated user
    +[apiInstance updateUserWith:username
    +    body:body
    +              completionHandler: ^(NSError* error) {
    +                            if (error) {
    +                                NSLog(@"Error: %@", error);
    +                            }
    +                        }];
    +
    +                                                    
    +
    +
    +
    
    +var  = require('');
    +
    +var api = new .UserApi()
    +
    +var username = username_example; // {String} name that need to be deleted
    +
    +var body = ; // {User} Updated user object
    +
    +
    +var callback = function(error, data, response) {
    +  if (error) {
    +    console.error(error);
    +  } else {
    +    console.log('API called successfully.');
    +  }
    +};
    +api.updateUser(username, body, callback);
    +
    +                                                    
    +
    + + + +
    +
    
    +using System;
    +using System.Diagnostics;
    +using .Api;
    +using .Client;
    +using ;
    +
    +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 );
    +            }
    +        }
    +    }
    +}
    +
    +                                                    
    +
    + + +
    +
    
    +updateUser($username, $body);
    +} catch (Exception $e) {
    +    echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL;
    +}
    +
    +                                                  
    +
    + +
    + + + + + +

    Parameters

    + + + +
    Path parameters
    + + + + + + + + + + +
    NameDescription
    username* + + + +
    +
    + + + +
    Body parameters
    + + + + + + + + + + + +
    NameDescription
    body * + + + +
    +
    + + +

    Responses

    + +

    Status: 400 - Invalid user supplied

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + +

    Status: 404 - User not found

    + + + + + + + + + +
    + + + +
    + + + + +
    + + +
    + + + + + + + +
    + + + + +
    + + + + + + + + + +
    + +
    + +
    + +
    + + + + + + +
    + + + + + + + +
    +
    + Generated 2016-10-13T09:03:51.792-07:00 +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + diff --git a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md index 9f609674c80..b670aa133b4 100644 --- a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md +++ b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md @@ -12,7 +12,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the `ContainerInterface` in a depency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md index 04eb3aea023..63cc3fb0f40 100644 --- a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md +++ b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md @@ -15,7 +15,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the delegate lookup feature in a dependency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c b/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c index 239c01d683d..821365bf127 100644 --- a/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c +++ b/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c @@ -419,7 +419,7 @@ static zval *pimple_object_read_dimension(zval *object, zval *offset, int type T } if (zend_hash_index_exists(&pimple_obj->factories, retval->handle_num)) { - /* Service is a factory, call it everytime and never cache its result */ + /* Service is a factory, call it every time and never cache its result */ PIMPLE_CALL_CB Z_DELREF_P(retval_ptr_ptr); /* fetch dim addr will increment refcount */ return retval_ptr_ptr; diff --git a/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php b/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php index 96d82cb81fb..639d9b9b470 100644 --- a/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php +++ b/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php @@ -110,7 +110,7 @@ public function add($callable) } /** - * Calling a non-existant method on App checks to see if there's an item + * Calling a non-existent method on App checks to see if there's an item * in the container that is callable and if so, calls it. * * @param string $method diff --git a/samples/server/petstore/aspnet5/.gitignore b/samples/server/petstore/aspnet5/.gitignore deleted file mode 100644 index e4349f244a1..00000000000 --- a/samples/server/petstore/aspnet5/.gitignore +++ /dev/null @@ -1 +0,0 @@ -artifacts/ \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/.swagger-codegen-ignore b/samples/server/petstore/aspnet5/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/aspnet5/.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/aspnet5/IO.Swagger.sln b/samples/server/petstore/aspnet5/IO.Swagger.sln new file mode 100644 index 00000000000..f376ce4f0f4 --- /dev/null +++ b/samples/server/petstore/aspnet5/IO.Swagger.sln @@ -0,0 +1,26 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFF6BF88-8A7D-4736-AF81-31BCE86B19BD}" + ProjectSection(SolutionItems) = preProject + global.json = global.json + EndProjectSection +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "{CF700387-34B9-4172-B648-7535827D5EEB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CF700387-34B9-4172-B648-7535827D5EEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.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/aspnet5/LICENSE b/samples/server/petstore/aspnet5/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/aspnet5/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/aspnet5/NuGet.Config b/samples/server/petstore/aspnet5/NuGet.Config new file mode 100644 index 00000000000..01f3d1f203f --- /dev/null +++ b/samples/server/petstore/aspnet5/NuGet.Config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/samples/server/petstore/aspnet5/README.md b/samples/server/petstore/aspnet5/README.md new file mode 100644 index 00000000000..3ed276e77b1 --- /dev/null +++ b/samples/server/petstore/aspnet5/README.md @@ -0,0 +1,25 @@ +# IO.Swagger - ASP.NET Core 1.0 Server + +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. + +## Run + +Linux/OS X: + +``` +sh build.sh +``` + +Windows: + +``` +build.bat +``` + +## Run in Docker + +``` +cd src/IO.Swagger +docker build -t IO.Swagger . +docker run -p 5000:5000 IO.Swagger +``` diff --git a/samples/server/petstore/aspnet5/build.bat b/samples/server/petstore/aspnet5/build.bat new file mode 100644 index 00000000000..85f9c4463e7 --- /dev/null +++ b/samples/server/petstore/aspnet5/build.bat @@ -0,0 +1,20 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + +@echo off + +dotnet restore src\IO.Swagger +dotnet build src\IO.Swagger +echo Now, run the following to start the project: dotnet run -p src\IO.Swagger\project.json web. +echo. diff --git a/samples/server/petstore/aspnet5/build.sh b/samples/server/petstore/aspnet5/build.sh old mode 100755 new mode 100644 index 5d6402baee7..f7592a16bb0 --- a/samples/server/petstore/aspnet5/build.sh +++ b/samples/server/petstore/aspnet5/build.sh @@ -1,17 +1,19 @@ #!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -if ! type dnvm > /dev/null 2>&1; then - source /usr/local/lib/dnx/bin/dnvm.sh -fi - -if ! type dnu > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then - dnvm install latest -runtime coreclr -alias default - dnvm install default -runtime mono -alias default -else - dnvm use default -runtime mono -fi - -dnu restore src/IO.Swagger/ && \ - dnu build src/IO.Swagger/ && \ - dnu pack src/IO.Swagger/ --out artifacts && \ - echo "Now, run the following to start the project: dnx --project src/IO.Swagger/project.json web" \ No newline at end of file +dotnet restore src/IO.Swagger/ && \ + dotnet build src/IO.Swagger/ && \ + echo "Now, run the following to start the project: dotnet run -p src/IO.Swagger/project.json web" \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/global.json b/samples/server/petstore/aspnet5/global.json index 4a6d1feac95..e5360d025ec 100644 --- a/samples/server/petstore/aspnet5/global.json +++ b/samples/server/petstore/aspnet5/global.json @@ -1,8 +1,7 @@ { - "projects": [ "src", "." ], + "projects": [ "src", "test" ], "sdk": { - "version": "1.0.0-rc1-final", - "runtime": "coreclr", - "architecture": "x64" + "version": "1.0.0-preview2-003121", + "runtime": "coreclr" } } \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs index 18fefec1cba..abac9871dc7 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +28,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using IO.Swagger.Models; @@ -26,7 +48,7 @@ public class PetApiController : Controller /// Pet object that needs to be added to the store /// Invalid input [HttpPost] - [Route("/pet")] + [Route("/v2/pet")] [SwaggerOperation("AddPet")] public virtual void AddPet([FromBody]Pet body) { @@ -42,7 +64,7 @@ public virtual void AddPet([FromBody]Pet body) /// /// Invalid pet value [HttpDelete] - [Route("/pet/{petId}")] + [Route("/v2/pet/{petId}")] [SwaggerOperation("DeletePet")] public virtual void DeletePet([FromRoute]long? petId, [FromHeader]string apiKey) { @@ -53,12 +75,12 @@ public virtual void DeletePet([FromRoute]long? petId, [FromHeader]string apiKey) /// /// Finds Pets by status /// - /// Multiple status values can be provided with comma seperated strings + /// Multiple status values can be provided with comma separated strings /// Status values that need to be considered for filter /// successful operation /// Invalid status value [HttpGet] - [Route("/pet/findByStatus")] + [Route("/v2/pet/findByStatus")] [SwaggerOperation("FindPetsByStatus")] [SwaggerResponse(200, type: typeof(List))] public virtual IActionResult FindPetsByStatus([FromQuery]List status) @@ -75,12 +97,12 @@ public virtual IActionResult FindPetsByStatus([FromQuery]List status) /// /// Finds Pets by tags /// - /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// Tags to filter by /// successful operation /// Invalid tag value [HttpGet] - [Route("/pet/findByTags")] + [Route("/v2/pet/findByTags")] [SwaggerOperation("FindPetsByTags")] [SwaggerResponse(200, type: typeof(List))] public virtual IActionResult FindPetsByTags([FromQuery]List tags) @@ -97,13 +119,13 @@ public virtual IActionResult FindPetsByTags([FromQuery]List tags) /// /// Find pet by ID /// - /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - /// ID of pet that needs to be fetched + /// Returns a single pet + /// ID of pet to return /// successful operation /// Invalid ID supplied /// Pet not found [HttpGet] - [Route("/pet/{petId}")] + [Route("/v2/pet/{petId}")] [SwaggerOperation("GetPetById")] [SwaggerResponse(200, type: typeof(Pet))] public virtual IActionResult GetPetById([FromRoute]long? petId) @@ -126,7 +148,7 @@ public virtual IActionResult GetPetById([FromRoute]long? petId) /// Pet not found /// Validation exception [HttpPut] - [Route("/pet")] + [Route("/v2/pet")] [SwaggerOperation("UpdatePet")] public virtual void UpdatePet([FromBody]Pet body) { @@ -143,9 +165,9 @@ public virtual void UpdatePet([FromBody]Pet body) /// Updated status of the pet /// Invalid input [HttpPost] - [Route("/pet/{petId}")] + [Route("/v2/pet/{petId}")] [SwaggerOperation("UpdatePetWithForm")] - public virtual void UpdatePetWithForm([FromRoute]string petId, [FromForm]string name, [FromForm]string status) + public virtual void UpdatePetWithForm([FromRoute]long? petId, [FromForm]string name, [FromForm]string status) { throw new NotImplementedException(); } @@ -158,13 +180,19 @@ public virtual void UpdatePetWithForm([FromRoute]string petId, [FromForm]string /// ID of pet to update /// Additional data to pass to server /// file to upload - /// successful operation + /// successful operation [HttpPost] - [Route("/pet/{petId}/uploadImage")] + [Route("/v2/pet/{petId}/uploadImage")] [SwaggerOperation("UploadFile")] - public virtual void UploadFile([FromRoute]long? petId, [FromForm]string additionalMetadata, [FromForm]System.IO.Stream file) + [SwaggerResponse(200, type: typeof(ApiResponse))] + public virtual IActionResult UploadFile([FromRoute]long? petId, [FromForm]string additionalMetadata, [FromForm]System.IO.Stream file) { - throw new NotImplementedException(); + string exampleJson = null; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(ApiResponse); + return new ObjectResult(example); } } } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs index 0ba31771bbb..da0b7b0d67a 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +28,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using IO.Swagger.Models; @@ -27,7 +49,7 @@ public class StoreApiController : Controller /// Invalid ID supplied /// Order not found [HttpDelete] - [Route("/store/order/{orderId}")] + [Route("/v2/store/order/{orderId}")] [SwaggerOperation("DeleteOrder")] public virtual void DeleteOrder([FromRoute]string orderId) { @@ -41,7 +63,7 @@ public virtual void DeleteOrder([FromRoute]string orderId) /// Returns a map of status codes to quantities /// successful operation [HttpGet] - [Route("/store/inventory")] + [Route("/v2/store/inventory")] [SwaggerOperation("GetInventory")] [SwaggerResponse(200, type: typeof(Dictionary))] public virtual IActionResult GetInventory() @@ -64,10 +86,10 @@ public virtual IActionResult GetInventory() /// Invalid ID supplied /// Order not found [HttpGet] - [Route("/store/order/{orderId}")] + [Route("/v2/store/order/{orderId}")] [SwaggerOperation("GetOrderById")] [SwaggerResponse(200, type: typeof(Order))] - public virtual IActionResult GetOrderById([FromRoute]string orderId) + public virtual IActionResult GetOrderById([FromRoute]long? orderId) { string exampleJson = null; @@ -86,7 +108,7 @@ public virtual IActionResult GetOrderById([FromRoute]string orderId) /// successful operation /// Invalid Order [HttpPost] - [Route("/store/order")] + [Route("/v2/store/order")] [SwaggerOperation("PlaceOrder")] [SwaggerResponse(200, type: typeof(Order))] public virtual IActionResult PlaceOrder([FromBody]Order body) diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs index b73cdd23c8f..023fc4366bc 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +28,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using IO.Swagger.Models; @@ -26,7 +48,7 @@ public class UserApiController : Controller /// Created user object /// successful operation [HttpPost] - [Route("/user")] + [Route("/v2/user")] [SwaggerOperation("CreateUser")] public virtual void CreateUser([FromBody]User body) { @@ -41,7 +63,7 @@ public virtual void CreateUser([FromBody]User body) /// List of user object /// successful operation [HttpPost] - [Route("/user/createWithArray")] + [Route("/v2/user/createWithArray")] [SwaggerOperation("CreateUsersWithArrayInput")] public virtual void CreateUsersWithArrayInput([FromBody]List body) { @@ -56,7 +78,7 @@ public virtual void CreateUsersWithArrayInput([FromBody]List body) /// List of user object /// successful operation [HttpPost] - [Route("/user/createWithList")] + [Route("/v2/user/createWithList")] [SwaggerOperation("CreateUsersWithListInput")] public virtual void CreateUsersWithListInput([FromBody]List body) { @@ -72,7 +94,7 @@ public virtual void CreateUsersWithListInput([FromBody]List body) /// Invalid username supplied /// User not found [HttpDelete] - [Route("/user/{username}")] + [Route("/v2/user/{username}")] [SwaggerOperation("DeleteUser")] public virtual void DeleteUser([FromRoute]string username) { @@ -89,7 +111,7 @@ public virtual void DeleteUser([FromRoute]string username) /// Invalid username supplied /// User not found [HttpGet] - [Route("/user/{username}")] + [Route("/v2/user/{username}")] [SwaggerOperation("GetUserByName")] [SwaggerResponse(200, type: typeof(User))] public virtual IActionResult GetUserByName([FromRoute]string username) @@ -112,7 +134,7 @@ public virtual IActionResult GetUserByName([FromRoute]string username) /// successful operation /// Invalid username/password supplied [HttpGet] - [Route("/user/login")] + [Route("/v2/user/login")] [SwaggerOperation("LoginUser")] [SwaggerResponse(200, type: typeof(string))] public virtual IActionResult LoginUser([FromQuery]string username, [FromQuery]string password) @@ -132,7 +154,7 @@ public virtual IActionResult LoginUser([FromQuery]string username, [FromQuery]st /// /// successful operation [HttpGet] - [Route("/user/logout")] + [Route("/v2/user/logout")] [SwaggerOperation("LogoutUser")] public virtual void LogoutUser() { @@ -149,7 +171,7 @@ public virtual void LogoutUser() /// Invalid user supplied /// User not found [HttpPut] - [Route("/user/{username}")] + [Route("/v2/user/{username}")] [SwaggerOperation("UpdateUser")] public virtual void UpdateUser([FromRoute]string username, [FromBody]User body) { diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile b/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile index af879b80ab0..f4abe48a5cb 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile @@ -1,10 +1,12 @@ -FROM microsoft/aspnet:1.0.0-rc1-final +FROM microsoft/dotnet:latest + +ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 RUN mkdir -p /app/IO.Swagger COPY . /app/IO.Swagger WORKDIR /app/IO.Swagger -RUN ["dnu", "restore"] -RUN ["dnu", "pack", "--out", "artifacts"] EXPOSE 5000/tcp -ENTRYPOINT ["dnx", "-p", "project.json", "web"] + +RUN ["dotnet", "restore"] +ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj b/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj new file mode 100644 index 00000000000..d8c2ce2535b --- /dev/null +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + {CF700387-34B9-4172-B648-7535827D5EEB} + IO.Swagger + .\obj + .\bin\ + v4.6 + + + 2.0 + + + \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs index 886f22c21bf..ab83518032c 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -11,8 +33,9 @@ namespace IO.Swagger.Models { /// - /// + /// Describes the result of uploading an image resource /// + [DataContract] public partial class ApiResponse : IEquatable { /// @@ -32,16 +55,19 @@ public ApiResponse(int? Code = null, string Type = null, string Message = null) /// /// Gets or Sets Code /// + [DataMember(Name="code")] public int? Code { get; set; } /// /// Gets or Sets Type /// + [DataMember(Name="type")] public string Type { get; set; } /// /// Gets or Sets Message /// + [DataMember(Name="message")] public string Message { get; set; } @@ -54,8 +80,8 @@ 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(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs index e412db81ee2..8e1404c7338 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -11,8 +33,9 @@ namespace IO.Swagger.Models { /// - /// + /// A category for a pet /// + [DataContract] public partial class Category : IEquatable { /// @@ -30,11 +53,13 @@ public Category(long? Id = null, string Name = null) /// /// Gets or Sets Id /// + [DataMember(Name="id")] public long? Id { get; set; } /// /// Gets or Sets Name /// + [DataMember(Name="name")] public string Name { get; set; } @@ -47,7 +72,7 @@ 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(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs index 80c3bcfb69e..b20143353cc 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -11,8 +33,9 @@ namespace IO.Swagger.Models { /// - /// + /// An order for a pets from the pet store /// + [DataContract] public partial class Order : IEquatable { /// @@ -23,7 +46,7 @@ public partial class Order : IEquatable /// Quantity. /// ShipDate. /// Order Status. - /// Complete. + /// Complete (default to false). public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, string Status = null, bool? Complete = null) { this.Id = Id; @@ -31,39 +54,53 @@ public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime this.Quantity = Quantity; this.ShipDate = ShipDate; this.Status = Status; - this.Complete = Complete; + // use default value if no "Complete" provided + if (Complete == null) + { + this.Complete = false; + } + else + { + this.Complete = Complete; + } } /// /// Gets or Sets Id /// + [DataMember(Name="id")] public long? Id { get; set; } /// /// Gets or Sets PetId /// + [DataMember(Name="petId")] public long? PetId { get; set; } /// /// Gets or Sets Quantity /// + [DataMember(Name="quantity")] public int? Quantity { get; set; } /// /// Gets or Sets ShipDate /// + [DataMember(Name="shipDate")] public DateTime? ShipDate { get; set; } /// /// Order Status /// /// Order Status + [DataMember(Name="status")] public string Status { get; set; } /// /// Gets or Sets Complete /// + [DataMember(Name="complete")] public bool? Complete { get; set; } @@ -76,11 +113,11 @@ 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(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs index 70a3992c294..9a6f87a2945 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -11,8 +33,9 @@ namespace IO.Swagger.Models { /// - /// + /// A pet for sale in the pet store /// + [DataContract] public partial class Pet : IEquatable { /// @@ -54,32 +77,38 @@ public Pet(long? Id = null, Category Category = null, string Name = null, List /// Gets or Sets Id /// + [DataMember(Name="id")] public long? Id { get; set; } /// /// Gets or Sets Category /// + [DataMember(Name="category")] public Category Category { get; set; } /// /// Gets or Sets Name /// + [DataMember(Name="name")] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// + [DataMember(Name="photoUrls")] public List PhotoUrls { get; set; } /// /// Gets or Sets Tags /// + [DataMember(Name="tags")] public List Tags { get; set; } /// /// pet status in the store /// /// pet status in the store + [DataMember(Name="status")] public string Status { get; set; } @@ -92,11 +121,11 @@ 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(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs index 77697097379..55269f40675 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -11,8 +33,9 @@ namespace IO.Swagger.Models { /// - /// + /// A tag for a pet /// + [DataContract] public partial class Tag : IEquatable { /// @@ -30,11 +53,13 @@ public Tag(long? Id = null, string Name = null) /// /// Gets or Sets Id /// + [DataMember(Name="id")] public long? Id { get; set; } /// /// Gets or Sets Name /// + [DataMember(Name="name")] public string Name { get; set; } @@ -47,7 +72,7 @@ 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(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs index c8373712db9..1dbde78cb0b 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -11,8 +33,9 @@ namespace IO.Swagger.Models { /// - /// + /// A User who is purchasing from the pet store /// + [DataContract] public partial class User : IEquatable { /// @@ -42,42 +65,50 @@ public User(long? Id = null, string Username = null, string FirstName = null, st /// /// Gets or Sets Id /// + [DataMember(Name="id")] public long? Id { get; set; } /// /// Gets or Sets Username /// + [DataMember(Name="username")] public string Username { get; set; } /// /// Gets or Sets FirstName /// + [DataMember(Name="firstName")] public string FirstName { get; set; } /// /// Gets or Sets LastName /// + [DataMember(Name="lastName")] public string LastName { get; set; } /// /// Gets or Sets Email /// + [DataMember(Name="email")] public string Email { get; set; } /// /// Gets or Sets Password /// + [DataMember(Name="password")] public string Password { get; set; } /// /// Gets or Sets Phone /// + [DataMember(Name="phone")] public string Phone { get; set; } /// /// User Status /// /// User Status + [DataMember(Name="userStatus")] public int? UserStatus { get; set; } @@ -90,13 +121,13 @@ 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(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs new file mode 100644 index 00000000000..8990e6b48ad --- /dev/null +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Builder; + +namespace IO.Swagger +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel(options => + { + // options.ThreadCount = 4; + // options.UseHttps("cert.pfx", "certpassword"); + options.NoDelay = true; + options.UseConnectionLogging(); + }) + .UseUrls("http://+:5000" /*, "https://+:5001" */) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json b/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json index 7d41a0f84b9..45a5f3319a5 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json @@ -1,12 +1,28 @@ { + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:50352/", + "sslPort": 0 + } + }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "swagger/ui", + "launchUrl": "swagger/ui/index.html", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "web": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "http://localhost:5000/swagger/ui/index.html", "environmentVariables": { - "ASPNET_ENV": "Development" + "ASPNETCORE_ENVIRONMENT": "Development" } } } -} +} \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs index 21cb3aa6042..e94c6e37d84 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs @@ -1,136 +1,102 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Hosting; +using System.Threading.Tasks; +using System.Xml.XPath; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.PlatformAbstractions; using Newtonsoft.Json.Serialization; -using Swashbuckle.SwaggerGen; -using Swashbuckle.SwaggerGen.XmlComments; +using Swashbuckle.Swagger.Model; +using Swashbuckle.SwaggerGen.Annotations; namespace IO.Swagger { public class Startup { private readonly IHostingEnvironment _hostingEnv; - private readonly IApplicationEnvironment _appEnv; - public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) + public IConfigurationRoot Configuration { get; } + + public Startup(IHostingEnvironment env) { _hostingEnv = env; - _appEnv = appEnv; - // Set up configuration sources. var builder = new ConfigurationBuilder() - .AddJsonFile("appsettings.json") + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } - - public IConfigurationRoot Configuration { get; set; } - + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - string xmlComments = string.Format(@"{0}{4}artifacts{4}{1}{4}{2}{3}{4}IO.Swagger.xml", - GetSolutionBasePath(), - _appEnv.Configuration, - _appEnv.RuntimeFramework.Identifier.ToLower(), - _appEnv.RuntimeFramework.Version.ToString().Replace(".", string.Empty), - Path.DirectorySeparatorChar); - // Add framework services. services.AddMvc() .AddJsonOptions( opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); - - // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. - // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. - // services.AddWebApiConventions(); - + services.AddSwaggerGen(); - services.ConfigureSwaggerDocument(options => + + services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "IO.Swagger", - Description = "IO.Swagger (ASP.NET 5 Web API 2.x)" + Description = "IO.Swagger (ASP.NET Core 1.0)" }); - - options.OperationFilter(new ApplyXmlActionCommentsFixed(xmlComments)); - }); - services.ConfigureSwaggerSchema(options => { - options.DescribeAllEnumsAsStrings = true; - options.ModelFilter(new ApplyXmlTypeCommentsFixed(xmlComments)); + options.DescribeAllEnumsAsStrings(); + + var comments = new XPathDocument($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml"); + options.OperationFilter(comments); + options.ModelFilter(comments); }); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); - app.UseIISPlatformHandler(); - + app.UseMvc(); + app.UseDefaultFiles(); app.UseStaticFiles(); - app.UseMvc(); - - app.UseSwaggerGen(); + app.UseSwagger(); app.UseSwaggerUi(); } - - // Taken from https://github.com/domaindrivendev/Ahoy/blob/master/test/WebSites/Basic/Startup.cs - private string GetSolutionBasePath() - { - var dir = Directory.CreateDirectory(_appEnv.ApplicationBasePath); - while (dir.Parent != null) - { - if (dir.GetDirectories("artifacts").Any()) - return dir.FullName; - - dir = dir.Parent; - } - throw new InvalidOperationException("Failed to detect solution base path - artifacts not found. Did you run dnu pack --out artifacts?"); - } - - // Entry point for the application. - public static void Main(string[] args) => WebApplication.Run(args); - } - - - // using Swashbuckle.SwaggerGen.XmlComments; - public class ApplyXmlTypeCommentsFixed : ApplyXmlTypeComments - { - public ApplyXmlTypeCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlTypeCommentsFixed(string filePath): base(filePath) - { - - } - } - - public class ApplyXmlActionCommentsFixed : ApplyXmlActionComments - { - public ApplyXmlActionCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlActionCommentsFixed(string filePath): base(filePath) - { - - } } -} \ No newline at end of file +} diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json b/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json index e5472e562b7..c6af7d9b069 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json @@ -2,7 +2,7 @@ "Logging": { "IncludeScopes": false, "LogLevel": { - "Default": "Verbose", + "Default": "Information", "System": "Information", "Microsoft": "Information" } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/project.json b/samples/server/petstore/aspnet5/src/IO.Swagger/project.json index 7317a7c0d0c..ca8ac967209 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/project.json +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/project.json @@ -1,41 +1,88 @@ { + "title": "Swagger UI", "version": "1.0.0-*", - "compilationOptions": { - "emitEntryPoint": true + "copyright": "IO.Swagger", + "description": "IO.Swagger", + "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0", + "type": "platform" + }, + "Microsoft.AspNetCore.Mvc": "1.0.0", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0", + "Microsoft.AspNetCore.StaticFiles": "1.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", + "Microsoft.Extensions.Configuration.Json": "1.0.0", + "Microsoft.Extensions.Logging": "1.0.0", + "Microsoft.Extensions.Logging.Console": "1.0.0", + "Microsoft.Extensions.Logging.Debug": "1.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", + "Microsoft.EntityFrameworkCore": "1.0.0", + "Swashbuckle.SwaggerGen": "6.0.0-beta901", + "Swashbuckle.SwaggerUi": "6.0.0-beta901" }, - "tooling": { - "defaultNamespace": "IO.Swagger" + + "tools": { + "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final", + + "Microsoft.Extensions.SecretManager.Tools": { + "imports": [ + "netstandard1.6", + "portable-net45+win8+dnxcore50", + "portable-net45+win8" + ], + "version": "1.0.0-preview2-final" + } }, - "dependencies": { - "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", - "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", - "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", - "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", - "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final", - "Microsoft.Extensions.Logging": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Debug" : "1.0.0-rc1-final", - "Swashbuckle.SwaggerGen": "6.0.0-rc1-final", - "Swashbuckle.SwaggerUi": "6.0.0-rc1-final" + "frameworks": { + "netcoreapp1.0": { + "imports": [ + "dotnet5.6", + "dnxcore50", + "netstandard1.6", + "portable-net452+win81" + ] + } }, - "commands": { - "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://0.0.0.0:5000" + "buildOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true, + "xmlDoc": true, + "compile": { + "exclude": [ + "wwwroot", + "node_modules", + "bower_components" + ] + } }, - "frameworks": { - "dnx451": { }, - "dnxcore50": { } + "runtimeOptions": { + "configProperties": { + "System.GC.Server": true + } + }, + + "publishOptions": { + "include": [ + "wwwroot", + "Views", + "Areas/**/Views", + "appsettings.json", + "web.config" + ], + "exclude": [ + "**.user", + "**.vspscc" + ] }, - "exclude": [ - "wwwroot", - "node_modules", - "bower_components" - ], - "publishExclude": [ - "**.user", - "**.vspscc" - ] + "scripts": { + "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] + } } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/web.config b/samples/server/petstore/aspnet5/src/IO.Swagger/web.config new file mode 100644 index 00000000000..a3b9f6add9c --- /dev/null +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/web.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + diff --git a/samples/server/petstore/erlang-server/.swagger-codegen-ignore b/samples/server/petstore/erlang-server/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/erlang-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/erlang-server/LICENSE b/samples/server/petstore/erlang-server/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/erlang-server/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/erlang-server/README.md b/samples/server/petstore/erlang-server/README.md new file mode 100644 index 00000000000..af53effabc7 --- /dev/null +++ b/samples/server/petstore/erlang-server/README.md @@ -0,0 +1,16 @@ +# Swagger rest server library for Erlang + +## Overview + +An Erlang server stub generated by [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) given an OpenAPI/Swagger spec. + +Dependency: [Cowboy](https://github.com/ninenines/cowboy) + +## Prerequisites + +TODO + +## Getting started + +TODO + diff --git a/samples/server/petstore/erlang-server/priv/swagger.json b/samples/server/petstore/erlang-server/priv/swagger.json new file mode 100644 index 00000000000..de3bdd27a50 --- /dev/null +++ b/samples/server/petstore/erlang-server/priv/swagger.json @@ -0,0 +1 @@ +{"swagger":"2.0","info":{"description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.","version":"1.0.0","title":"Swagger Petstore","termsOfService":"http://swagger.io/terms/","contact":{"email":"apiteam@swagger.io"},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0.html"}},"host":"petstore.swagger.io","basePath":"/v2","tags":[{"name":"pet","description":"Everything about your Pets","externalDocs":{"description":"Find out more","url":"http://swagger.io"}},{"name":"store","description":"Access to Petstore orders"},{"name":"user","description":"Operations about user","externalDocs":{"description":"Find out more about our store","url":"http://swagger.io"}}],"schemes":["http"],"paths":{"/pet":{"post":{"tags":["pet"],"summary":"Add a new pet to the store","description":"","operationId":"addPet","consumes":["application/json","application/xml"],"produces":["application/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"put":{"tags":["pet"],"summary":"Update an existing pet","description":"","operationId":"updatePet","consumes":["application/json","application/xml"],"produces":["application/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"},"405":{"description":"Validation exception"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByStatus":{"get":{"tags":["pet"],"summary":"Finds Pets by status","description":"Multiple status values can be provided with comma separated strings","operationId":"findPetsByStatus","produces":["application/xml","application/json"],"parameters":[{"name":"status","in":"query","description":"Status values that need to be considered for filter","required":true,"type":"array","items":{"type":"string","default":"available","enum":["available","pending","sold"]},"collectionFormat":"csv"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid status value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByTags":{"get":{"tags":["pet"],"summary":"Finds Pets by tags","description":"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.","operationId":"findPetsByTags","produces":["application/xml","application/json"],"parameters":[{"name":"tags","in":"query","description":"Tags to filter by","required":true,"type":"array","items":{"type":"string"},"collectionFormat":"csv"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid tag value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/{petId}":{"get":{"tags":["pet"],"summary":"Find pet by ID","description":"Returns a single pet","operationId":"getPetById","produces":["application/xml","application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to return","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Pet"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"api_key":[]}]},"post":{"tags":["pet"],"summary":"Updates a pet in the store with form data","description":"","operationId":"updatePetWithForm","consumes":["application/x-www-form-urlencoded"],"produces":["application/xml","application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet that needs to be updated","required":true,"type":"integer","format":"int64"},{"name":"name","in":"formData","description":"Updated name of the pet","required":false,"type":"string"},{"name":"status","in":"formData","description":"Updated status of the pet","required":false,"type":"string"}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"delete":{"tags":["pet"],"summary":"Deletes a pet","description":"","operationId":"deletePet","produces":["application/xml","application/json"],"parameters":[{"name":"api_key","in":"header","required":false,"type":"string"},{"name":"petId","in":"path","description":"Pet id to delete","required":true,"type":"integer","format":"int64"}],"responses":{"400":{"description":"Invalid pet value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/{petId}/uploadImage":{"post":{"tags":["pet"],"summary":"uploads an image","description":"","operationId":"uploadFile","consumes":["multipart/form-data"],"produces":["application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to update","required":true,"type":"integer","format":"int64"},{"name":"additionalMetadata","in":"formData","description":"Additional data to pass to server","required":false,"type":"string"},{"name":"file","in":"formData","description":"file to upload","required":false,"type":"file"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiResponse"}}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/store/inventory":{"get":{"tags":["store"],"summary":"Returns pet inventories by status","description":"Returns a map of status codes to quantities","operationId":"getInventory","produces":["application/json"],"parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}}},"security":[{"api_key":[]}]}},"/store/order":{"post":{"tags":["store"],"summary":"Place an order for a pet","description":"","operationId":"placeOrder","produces":["application/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"order placed for purchasing the pet","required":true,"schema":{"$ref":"#/definitions/Order"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid Order"}}}},"/store/order/{orderId}":{"get":{"tags":["store"],"summary":"Find purchase order by ID","description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions","operationId":"getOrderById","produces":["application/xml","application/json"],"parameters":[{"name":"orderId","in":"path","description":"ID of pet that needs to be fetched","required":true,"type":"integer","maximum":5.0,"minimum":1.0,"format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}},"delete":{"tags":["store"],"summary":"Delete purchase order by ID","description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors","operationId":"deleteOrder","produces":["application/xml","application/json"],"parameters":[{"name":"orderId","in":"path","description":"ID of the order that needs to be deleted","required":true,"type":"string","minimum":1.0}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}}},"/user":{"post":{"tags":["user"],"summary":"Create user","description":"This can only be done by the logged in user.","operationId":"createUser","produces":["application/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"Created user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"default":{"description":"successful operation"}}}},"/user/createWithArray":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithArrayInput","produces":["application/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/createWithList":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithListInput","produces":["application/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/login":{"get":{"tags":["user"],"summary":"Logs user into the system","description":"","operationId":"loginUser","produces":["application/xml","application/json"],"parameters":[{"name":"username","in":"query","description":"The user name for login","required":true,"type":"string"},{"name":"password","in":"query","description":"The password for login in clear text","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"type":"string"},"headers":{"X-Rate-Limit":{"type":"integer","format":"int32","description":"calls per hour allowed by the user"},"X-Expires-After":{"type":"string","format":"date-time","description":"date in UTC when toekn expires"}}},"400":{"description":"Invalid username/password supplied"}}}},"/user/logout":{"get":{"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","produces":["application/xml","application/json"],"parameters":[],"responses":{"default":{"description":"successful operation"}}}},"/user/{username}":{"get":{"tags":["user"],"summary":"Get user by user name","description":"","operationId":"getUserByName","produces":["application/xml","application/json"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be fetched. Use user1 for testing. ","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/User"}},"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}},"put":{"tags":["user"],"summary":"Updated user","description":"This can only be done by the logged in user.","operationId":"updateUser","produces":["application/xml","application/json"],"parameters":[{"name":"username","in":"path","description":"name that need to be deleted","required":true,"type":"string"},{"in":"body","name":"body","description":"Updated user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"400":{"description":"Invalid user supplied"},"404":{"description":"User not found"}}},"delete":{"tags":["user"],"summary":"Delete user","description":"This can only be done by the logged in user.","operationId":"deleteUser","produces":["application/xml","application/json"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be deleted","required":true,"type":"string"}],"responses":{"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}}}},"securityDefinitions":{"api_key":{"type":"apiKey","name":"api_key","in":"header"},"petstore_auth":{"type":"oauth2","authorizationUrl":"http://petstore.swagger.io/api/oauth/dialog","flow":"implicit","scopes":{"write:pets":"modify pets in your account","read:pets":"read your pets"}}},"definitions":{"Order":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"petId":{"type":"integer","format":"int64"},"quantity":{"type":"integer","format":"int32"},"shipDate":{"type":"string","format":"date-time"},"status":{"type":"string","description":"Order Status","enum":["placed","approved","delivered"]},"complete":{"type":"boolean","default":false}},"xml":{"name":"Order"}},"Category":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Category"}},"User":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"username":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string"},"password":{"type":"string"},"phone":{"type":"string"},"userStatus":{"type":"integer","format":"int32","description":"User Status"}},"xml":{"name":"User"}},"Tag":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Tag"}},"Pet":{"type":"object","required":["name","photoUrls"],"properties":{"id":{"type":"integer","format":"int64"},"category":{"$ref":"#/definitions/Category"},"name":{"type":"string","example":"doggie"},"photoUrls":{"type":"array","xml":{"name":"photoUrl","wrapped":true},"items":{"type":"string"}},"tags":{"type":"array","xml":{"name":"tag","wrapped":true},"items":{"$ref":"#/definitions/Tag"}},"status":{"type":"string","description":"pet status in the store","enum":["available","pending","sold"]}},"xml":{"name":"Pet"}},"ApiResponse":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"type":{"type":"string"},"message":{"type":"string"}}}},"externalDocs":{"description":"Find out more about Swagger","url":"http://swagger.io"}} diff --git a/samples/server/petstore/erlang-server/rebar.config b/samples/server/petstore/erlang-server/rebar.config new file mode 100644 index 00000000000..1c7f7d922e9 --- /dev/null +++ b/samples/server/petstore/erlang-server/rebar.config @@ -0,0 +1,4 @@ +{deps, [ + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "v2.8.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.4.0"}}} +]}. diff --git a/samples/server/petstore/erlang-server/src/swagger.app.src b/samples/server/petstore/erlang-server/src/swagger.app.src new file mode 100644 index 00000000000..9016bde7219 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger.app.src @@ -0,0 +1,19 @@ +{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, "1.0.0"}, + {registered, []}, + {applications, [ + kernel, + stdlib, + ssl, + inets, + jsx, + jesse, + cowboy + ]}, + {env, [ + ]}, + {modules, []}, + {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 new file mode 100644 index 00000000000..b3020fbbf69 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_api.erl @@ -0,0 +1,733 @@ +-module(swagger_api). + +-export([request_params/1]). +-export([request_param_info/2]). +-export([populate_request/3]). +-export([validate_response/4]). + +-type operation_id() :: atom(). +-type request_param() :: atom(). + +-export_type([operation_id/0]). + +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. + + +request_params('AddPet') -> + [ + 'Pet' + ]; + +request_params('DeletePet') -> + [ + 'petId', + 'api_key' + ]; + +request_params('FindPetsByStatus') -> + [ + 'status' + ]; + +request_params('FindPetsByTags') -> + [ + 'tags' + ]; + +request_params('GetPetById') -> + [ + 'petId' + ]; + +request_params('UpdatePet') -> + [ + 'Pet' + ]; + +request_params('UpdatePetWithForm') -> + [ + 'petId', + 'name', + 'status' + ]; + +request_params('UploadFile') -> + [ + 'petId', + 'additionalMetadata', + 'file' + ]; + + +request_params('DeleteOrder') -> + [ + 'orderId' + ]; + +request_params('GetInventory') -> + [ + ]; + +request_params('GetOrderById') -> + [ + 'orderId' + ]; + +request_params('PlaceOrder') -> + [ + 'Order' + ]; + + +request_params('CreateUser') -> + [ + 'User' + ]; + +request_params('CreateUsersWithArrayInput') -> + [ + 'list' + ]; + +request_params('CreateUsersWithListInput') -> + [ + 'list' + ]; + +request_params('DeleteUser') -> + [ + 'username' + ]; + +request_params('GetUserByName') -> + [ + 'username' + ]; + +request_params('LoginUser') -> + [ + 'username', + 'password' + ]; + +request_params('LogoutUser') -> + [ + ]; + +request_params('UpdateUser') -> + [ + 'username', + 'User' + ]; + +request_params(_) -> + error(unknown_operation). + +-type rule() :: + {type, 'binary'} | + {type, 'integer'} | + {type, 'float'} | + {type, 'binary'} | + {type, 'boolean'} | + {type, 'date'} | + {type, 'datetime'} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ + source => qs_val | binding | header | body, + rules => [rule()] +}. + + + +request_param_info('AddPet', 'Pet') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('DeletePet', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('DeletePet', 'api_key') -> + #{ + source => header, + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('FindPetsByStatus', 'status') -> + #{ + source => qs_val , + rules => [ + {enum, ['available', 'pending', 'sold'] }, + required + ] + }; + +request_param_info('FindPetsByTags', 'tags') -> + #{ + source => qs_val , + rules => [ + required + ] + }; + +request_param_info('GetPetById', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('UpdatePet', 'Pet') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('UpdatePetWithForm', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('UpdatePetWithForm', 'name') -> + #{ + source => , + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('UpdatePetWithForm', 'status') -> + #{ + source => , + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('UploadFile', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('UploadFile', 'additionalMetadata') -> + #{ + source => , + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('UploadFile', 'file') -> + #{ + source => , + rules => [ + not_required + ] + }; + + +request_param_info('DeleteOrder', 'orderId') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + {min, 1.0 }, + required + ] + }; + +request_param_info('GetOrderById', 'orderId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + {max, 5.0 }, + {min, 1.0 }, + required + ] + }; + +request_param_info('PlaceOrder', 'Order') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + + +request_param_info('CreateUser', 'User') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('CreateUsersWithArrayInput', 'list') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('CreateUsersWithListInput', 'list') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('DeleteUser', 'username') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('GetUserByName', 'username') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('LoginUser', 'username') -> + #{ + source => qs_val , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('LoginUser', 'password') -> + #{ + source => qs_val , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('UpdateUser', 'username') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('UpdateUser', 'User') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info(OperationID, Name) -> + error({unknown_param, OperationID, Name}). + +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state() +) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. + +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +populate_request_params(_, [], Req, _, Model) -> + {ok, Model, Req}; + +populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> + case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of + {ok, K, V, Req} -> + populate_request_params(OperationID, T, Req, ValidatorState, maps:put(K, V, Model)); + Error -> + Error + end. + +populate_request_param(OperationID, Name, Req0, ValidatorState) -> + #{rules := Rules, source := Source} = request_param_info(OperationID, Name), + {Value, Req} = get_value(Source, Name, Req0), + case prepare_param(Rules, Name, Value, ValidatorState) of + {ok, Result} -> {ok, Name, Result, Req}; + {error, Reason} -> + {error, Reason, Req} + end. + +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state() +) -> ok | no_return(). + + +validate_response('AddPet', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('DeletePet', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('FindPetsByStatus', 200, Body, ValidatorState) -> + validate_response_body('list', 'Pet', Body, ValidatorState); +validate_response('FindPetsByStatus', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('FindPetsByTags', 200, Body, ValidatorState) -> + validate_response_body('list', 'Pet', Body, ValidatorState); +validate_response('FindPetsByTags', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('GetPetById', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('GetPetById', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetPetById', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UpdatePet', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UpdatePetWithForm', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UploadFile', 200, Body, ValidatorState) -> + validate_response_body('ApiResponse', 'ApiResponse', Body, ValidatorState); + + +validate_response('DeleteOrder', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteOrder', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('GetInventory', 200, Body, ValidatorState) -> + validate_response_body('map', 'integer', Body, ValidatorState); + +validate_response('GetOrderById', 200, Body, ValidatorState) -> + validate_response_body('Order', 'Order', Body, ValidatorState); +validate_response('GetOrderById', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetOrderById', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('PlaceOrder', 200, Body, ValidatorState) -> + validate_response_body('Order', 'Order', Body, ValidatorState); +validate_response('PlaceOrder', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + + +validate_response('CreateUser', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('CreateUsersWithArrayInput', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('CreateUsersWithListInput', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('DeleteUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteUser', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('GetUserByName', 200, Body, ValidatorState) -> + validate_response_body('User', 'User', Body, ValidatorState); +validate_response('GetUserByName', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetUserByName', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('LoginUser', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('LoginUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('LogoutUser', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UpdateUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdateUser', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + + +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> + [ + validate(schema, ReturnBaseType, Item, ValidatorState) + || Item <- Body]; + +validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> + validate(schema, ReturnBaseType, Body, ValidatorState). + +%%% +validate(Rule = required, Name, Value, _ValidatorState) -> + case Value of + undefined -> validation_error(Rule, Name); + _ -> ok + end; + +validate(not_required, _Name, _Value, _ValidatorState) -> + ok; + +validate(_, _Name, undefined, _ValidatorState) -> + ok; + +validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> + try + {ok, swagger_utils:to_int(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> + try + {ok, swagger_utils:to_float(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> + {ok, Value}; + +validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> + V = binary_to_lower(Value), + try + case binary_to_existing_atom(V, utf8) of + B when is_boolean(B) -> {ok, B}; + _ -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> + try + FormattedValue = erlang:binary_to_existing_atom(Value, utf8), + case lists:member(FormattedValue, Values) of + true -> {ok, FormattedValue}; + false -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> + case Value >= Max of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> + case Value > ExclusiveMax of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> + case Value =< Min of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> + case Value =< ExclusiveMin of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> + case size(Value) =< MaxLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> + case size(Value) >= MinLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> + {ok, MP} = re:compile(Pattern), + case re:run(Value, MP) of + {match, _} -> ok; + _ -> validation_error(Rule, Name) + end; + +validate(Rule = schema, Name, Value, ValidatorState) -> + Definition = list_to_binary("#/definitions/" ++ swagger_utils:to_list(Name)), + try + _ = validate_with_schema(Value, Definition, ValidatorState), + ok + catch + throw:[{schema_invalid, _, Error} | _] -> + Info = #{ + type => schema_invalid, + error => Error + }, + validation_error(Rule, Name, Info); + throw:[{data_invalid, Schema, Error, _, Path} | _] -> + Info = #{ + type => data_invalid, + error => Error, + schema => Schema, + path => Path + }, + validation_error(Rule, Name, Info) + end; + +validate(Rule, Name, _Value, _ValidatorState) -> + error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + error({unknown_validation_rule, Rule}). + +-spec validation_error(Rule :: any(), Name :: any()) -> no_return(). + +validation_error(ViolatedRule, Name) -> + validation_error(ViolatedRule, Name, #{}). + +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). + +validation_error(ViolatedRule, Name, Info) -> + throw({wrong_param, Name, ViolatedRule, Info}). + +get_value(body, _Name, Req0) -> + {ok, Body, Req} = cowboy_req:body(Req0), + Value = prepare_body(Body), + {Value, Req}; + +get_value(qs_val, Name, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + Value = swagger_utils:get_opt(swagger_utils:to_qs(Name), QS), + {Value, Req}; + +get_value(header, Name, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + Value = swagger_utils:get_opt(swagger_utils:to_header(Name), Headers), + {Value, Req}; + +get_value(binding, Name, Req0) -> + {Bindings, Req} = cowboy_req:bindings(Req0), + Value = swagger_utils:get_opt(swagger_utils:to_binding(Name), Bindings), + {Value, Req}. + +prepare_body(Body) -> + case Body of + <<"">> -> <<"">>; + _ -> jsx:decode(Body, [return_maps]) + end. + +validate_with_schema(Body, Definition, ValidatorState) -> + jesse_schema_validator:validate_with_state( + [{<<"$ref">>, Definition}], + Body, + ValidatorState + ). + +prepare_param(Rules, Name, Value, ValidatorState) -> + try + Result = lists:foldl( + fun(Rule, Acc) -> + case validate(Rule, Name, Acc, ValidatorState) of + ok -> Acc; + {ok, Prepared} -> Prepared + end + end, + Value, + Rules + ), + {ok, Result} + catch + throw:Reason -> + {error, Reason} + end. + +binary_to_lower(V) when is_binary(V) -> + list_to_binary(string:to_lower(swagger_utils:to_list(V))). diff --git a/samples/server/petstore/erlang-server/src/swagger_auth.erl b/samples/server/petstore/erlang-server/src/swagger_auth.erl new file mode 100644 index 00000000000..275ad19f38f --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_auth.erl @@ -0,0 +1,50 @@ +-module(swagger_auth). + +-export([authorize_api_key/5]). + +-spec authorize_api_key( + LogicHandler :: atom(), + OperationID :: swagger_api:operation_id(), + From :: header | qs_val, + KeyParam :: iodata() | atom(), + Req ::cowboy_req:req() +)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | + {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. + +authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> + {ApiKey, Req} = get_api_key(From, KeyParam, Req0), + case ApiKey of + undefined -> + AuthHeader = <<"">>, + {false, AuthHeader, Req}; + _ -> + Result = swagger_logic_handler:authorize_api_key( + LogicHandler, + OperationID, + ApiKey + ), + case Result of + {true, Context} -> + {true, Context, Req}; + false -> + AuthHeader = <<"">>, + {false, AuthHeader, Req} + end + end. + +get_api_key(header, KeyParam, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + { + swagger_utils:get_opt( + swagger_utils:to_header(KeyParam), + Headers + ), + Req + }; + +get_api_key(qs_val, KeyParam, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + { swagger_utils:get_opt(KeyParam, QS), Req}. + + + diff --git a/samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl b/samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl new file mode 100644 index 00000000000..b68b8c00cdb --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl @@ -0,0 +1,24 @@ +-module(swagger_default_logic_handler). + +-behaviour(swagger_logic_handler). + +-export([handle_request/3]). +-export([authorize_api_key/2]). + +-spec authorize_api_key(OperationID :: swagger_api:operation_id(), ApiKey :: binary()) -> {true, #{}}. + +authorize_api_key(_, _) -> {true, #{}}. + +-spec handle_request( + OperationID :: swagger_api:operation_id(), + Req :: cowboy_req:req(), + Context :: #{} +) -> + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: #{}}. + +handle_request(OperationID, Req, Context) -> + error_logger:error_msg( + "Got not implemented request to process: ~p~n", + [{OperationID, Req, Context}] + ), + {501, [], #{}}. diff --git a/samples/server/petstore/erlang-server/src/swagger_logic_handler.erl b/samples/server/petstore/erlang-server/src/swagger_logic_handler.erl new file mode 100644 index 00000000000..4ff40c85ec6 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_logic_handler.erl @@ -0,0 +1,38 @@ +-module(swagger_logic_handler). + +-export([handle_request/4]). +-export([authorize_api_key/3]). +-type context() :: #{binary() => any()}. +-type handler_response() ::{ + Status :: cowboy:http_status(), + Headers :: cowboy:http_headers(), + Body :: #{} +}. + +-export_type([handler_response/0]). + +-callback authorize_api_key( + OperationID :: swagger_api:operation_id(), + ApiKey :: binary() +) -> + Result :: boolean() | {boolean(), context()}. + + +-callback handle_request(OperationID :: swagger_api:operation_id(), Request :: any(), Context :: context()) -> + handler_response(). + +-spec handle_request( + Handler :: atom(), + OperationID :: swagger_api:operation_id(), + Request :: any(), + Context :: context() +) -> + handler_response(). + +handle_request(Handler, OperationID, Req, Context) -> + Handler:handle_request(OperationID, Req, Context). + +-spec authorize_api_key(Handler :: atom(), OperationID :: swagger_api:operation_id(), ApiKey :: binary()) -> + Result :: false | {true, context()}. +authorize_api_key(Handler, OperationID, ApiKey) -> + Handler:authorize_api_key(OperationID, ApiKey). diff --git a/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl b/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl new file mode 100644 index 00000000000..4351da7da6c --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl @@ -0,0 +1,408 @@ +%% basic handler +-module(swagger_pet_handler). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: swagger_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + + +allowed_methods( + Req, + State = #state{ + operation_id = 'AddPet' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'DeletePet' + } +) -> + {[<<"DELETE">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'FindPetsByStatus' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'FindPetsByTags' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetPetById' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UpdatePet' + } +) -> + {[<<"PUT">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UpdatePetWithForm' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UploadFile' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. + +is_authorized( + Req0, + State = #state{ + operation_id = 'AddPet' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'DeletePet' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'FindPetsByStatus' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'FindPetsByTags' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetPetById' = OperationID, + logic_handler = LogicHandler + } +) -> + From = header, + Result = swagger_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "api_key", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + +is_authorized( + Req0, + State = #state{ + operation_id = 'UpdatePet' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'UpdatePetWithForm' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'UploadFile' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'AddPet' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'DeletePet' + } +) -> + Headers = ["api_key"], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'FindPetsByStatus' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'FindPetsByTags' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetPetById' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UpdatePet' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UpdatePetWithForm' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UploadFile' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case swagger_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = swagger_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = swagger_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/samples/server/petstore/erlang-server/src/swagger_router.erl b/samples/server/petstore/erlang-server/src/swagger_router.erl new file mode 100644 index 00000000000..7a1b004a5f2 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_router.erl @@ -0,0 +1,169 @@ +-module(swagger_router). + +-export([get_paths/1]). + +-type operations() :: #{ + Method :: binary() => swagger_api:operation_id() +}. + +-type init_opts() :: { + Operations :: operations(), + LogicHandler :: atom(), + ValidatorState :: jesse_state:state() +}. + +-export_type([init_opts/0]). + +-spec get_paths(LogicHandler :: atom()) -> [{'_',[{ + Path :: string(), + Handler :: atom(), + InitOpts :: init_opts() +}]}]. + +get_paths(LogicHandler) -> + ValidatorState = prepare_validator(), + PreparedPaths = maps:fold( + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, + [], + group_paths() + ), + [ + {'_', + [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] + } + ]. + +group_paths() -> + maps:fold( + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, + #{}, + get_operations() + ). + +get_operations() -> + #{ + 'AddPet' => #{ + path => "/v2/pet", + method => <<"POST">>, + handler => 'swagger_pet_handler' + }, + 'DeletePet' => #{ + path => "/v2/pet/:petId", + method => <<"DELETE">>, + handler => 'swagger_pet_handler' + }, + 'FindPetsByStatus' => #{ + path => "/v2/pet/findByStatus", + method => <<"GET">>, + handler => 'swagger_pet_handler' + }, + 'FindPetsByTags' => #{ + path => "/v2/pet/findByTags", + method => <<"GET">>, + handler => 'swagger_pet_handler' + }, + 'GetPetById' => #{ + path => "/v2/pet/:petId", + method => <<"GET">>, + handler => 'swagger_pet_handler' + }, + 'UpdatePet' => #{ + path => "/v2/pet", + method => <<"PUT">>, + handler => 'swagger_pet_handler' + }, + 'UpdatePetWithForm' => #{ + path => "/v2/pet/:petId", + method => <<"POST">>, + handler => 'swagger_pet_handler' + }, + 'UploadFile' => #{ + path => "/v2/pet/:petId/uploadImage", + method => <<"POST">>, + handler => 'swagger_pet_handler' + }, + 'DeleteOrder' => #{ + path => "/v2/store/order/:orderId", + method => <<"DELETE">>, + handler => 'swagger_store_handler' + }, + 'GetInventory' => #{ + path => "/v2/store/inventory", + method => <<"GET">>, + handler => 'swagger_store_handler' + }, + 'GetOrderById' => #{ + path => "/v2/store/order/:orderId", + method => <<"GET">>, + handler => 'swagger_store_handler' + }, + 'PlaceOrder' => #{ + path => "/v2/store/order", + method => <<"POST">>, + handler => 'swagger_store_handler' + }, + 'CreateUser' => #{ + path => "/v2/user", + method => <<"POST">>, + handler => 'swagger_user_handler' + }, + 'CreateUsersWithArrayInput' => #{ + path => "/v2/user/createWithArray", + method => <<"POST">>, + handler => 'swagger_user_handler' + }, + 'CreateUsersWithListInput' => #{ + path => "/v2/user/createWithList", + method => <<"POST">>, + handler => 'swagger_user_handler' + }, + 'DeleteUser' => #{ + path => "/v2/user/:username", + method => <<"DELETE">>, + handler => 'swagger_user_handler' + }, + 'GetUserByName' => #{ + path => "/v2/user/:username", + method => <<"GET">>, + handler => 'swagger_user_handler' + }, + 'LoginUser' => #{ + path => "/v2/user/login", + method => <<"GET">>, + handler => 'swagger_user_handler' + }, + 'LogoutUser' => #{ + path => "/v2/user/logout", + method => <<"GET">>, + handler => 'swagger_user_handler' + }, + 'UpdateUser' => #{ + path => "/v2/user/:username", + method => <<"PUT">>, + handler => 'swagger_user_handler' + } + }. + +prepare_validator() -> + R = jsx:decode(element(2, file:read_file(get_swagger_path()))), + jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]). + + +get_swagger_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join(swagger_utils:priv_dir(AppName), "swagger.json"). + + diff --git a/samples/server/petstore/erlang-server/src/swagger_server.erl b/samples/server/petstore/erlang-server/src/swagger_server.erl new file mode 100644 index 00000000000..4f56a326034 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_server.erl @@ -0,0 +1,64 @@ +-module(swagger_server). + + +-define(DEFAULT_ACCEPTORS_POOLSIZE, 100). +-define(DEFAULT_LOGIC_HANDLER, swagger_default_logic_handler). + +-export([child_spec/2]). + +-spec child_spec( ID :: any(), #{ + ip => inet:ip_address(), + port => inet:port_number(), + net_opts => [] +}) -> supervisor:child_spec(). + +child_spec(ID, #{ + ip := IP , + port := Port, + net_opts := NetOpts +} = Params) -> + AcceptorsPool = ?DEFAULT_ACCEPTORS_POOLSIZE, + {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), + LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), + ExtraOpts = maps:get(cowboy_extra_opts, Params, []), + CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + ranch:child_spec({?MODULE, ID}, AcceptorsPool, + Transport, TransportOpts, cowboy_protocol, CowboyOpts). + +get_socket_transport(IP, Port, Options) -> + Opts = [ + {ip, IP}, + {port, Port} + ], + case swagger_utils:get_opt(ssl, Options) of + SslOpts = [_|_] -> + {ranch_ssl, Opts ++ SslOpts}; + undefined -> + {ranch_tcp, Opts} + end. + +get_cowboy_config(LogicHandler, ExtraOpts) -> + get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). + +get_cowboy_config(_LogicHandler, [], Opts) -> + Opts; + +get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> + NewEnv = case proplists:get_value(dispatch, Env) of + undefined -> [get_default_dispatch(LogicHandler) | Env]; + _ -> Env + end, + get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); + +get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> + get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). + +get_default_dispatch(LogicHandler) -> + Paths = swagger_router:get_paths(LogicHandler), + {dispatch, cowboy_router:compile(Paths)}. + +get_default_opts(LogicHandler) -> + [{env, [get_default_dispatch(LogicHandler)]}]. + +store_key(Key, Value, Opts) -> + lists:keystore(Key, 1, Opts, {Key, Value}). diff --git a/samples/server/petstore/erlang-server/src/swagger_store_handler.erl b/samples/server/petstore/erlang-server/src/swagger_store_handler.erl new file mode 100644 index 00000000000..d70470d6384 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_store_handler.erl @@ -0,0 +1,304 @@ +%% basic handler +-module(swagger_store_handler). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: swagger_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + + +allowed_methods( + Req, + State = #state{ + operation_id = 'DeleteOrder' + } +) -> + {[<<"DELETE">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetInventory' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetOrderById' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'PlaceOrder' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. + +is_authorized( + Req0, + State = #state{ + operation_id = 'DeleteOrder' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetInventory' = OperationID, + logic_handler = LogicHandler + } +) -> + From = header, + Result = swagger_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "api_key", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetOrderById' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'PlaceOrder' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'DeleteOrder' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetInventory' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetOrderById' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'PlaceOrder' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case swagger_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = swagger_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = swagger_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/samples/server/petstore/erlang-server/src/swagger_user_handler.erl b/samples/server/petstore/erlang-server/src/swagger_user_handler.erl new file mode 100644 index 00000000000..11c8d659416 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_user_handler.erl @@ -0,0 +1,396 @@ +%% basic handler +-module(swagger_user_handler). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: swagger_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + + +allowed_methods( + Req, + State = #state{ + operation_id = 'CreateUser' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'CreateUsersWithArrayInput' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'CreateUsersWithListInput' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'DeleteUser' + } +) -> + {[<<"DELETE">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetUserByName' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'LoginUser' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'LogoutUser' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UpdateUser' + } +) -> + {[<<"PUT">>], Req, State}; + +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. + +is_authorized( + Req0, + State = #state{ + operation_id = 'CreateUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'CreateUsersWithArrayInput' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'CreateUsersWithListInput' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'DeleteUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetUserByName' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'LoginUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'LogoutUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'UpdateUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'CreateUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'CreateUsersWithArrayInput' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'CreateUsersWithListInput' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'DeleteUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetUserByName' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'LoginUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'LogoutUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UpdateUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case swagger_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = swagger_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = swagger_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/samples/server/petstore/erlang-server/src/swagger_utils.erl b/samples/server/petstore/erlang-server/src/swagger_utils.erl new file mode 100644 index 00000000000..f7897fddd84 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_utils.erl @@ -0,0 +1,173 @@ +-module(swagger_utils). + +-export([to_binary/1]). +-export([to_list/1]). +-export([to_float/1]). +-export([to_int/1]). +-export([to_lower/1]). +-export([to_upper/1]). +-export([set_resp_headers/2]). +-export([to_header/1]). +-export([to_qs/1]). +-export([to_binding/1]). +-export([get_opt/2]). +-export([get_opt/3]). +-export([priv_dir/0]). +-export([priv_dir/1]). +-export([priv_path/1]). + + +-spec to_binary(iodata() | atom() | number()) -> binary(). + +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> string(). + +to_list(V) when is_list(V) -> V; +to_list(V) -> binary_to_list(to_binary(V)). + +-spec to_float(iodata()) -> number(). + +to_float(V) -> + Data = iolist_to_binary([V]), + case binary:split(Data, <<$.>>) of + [Data] -> + binary_to_integer(Data); + [<<>>, _] -> + binary_to_float(<<$0, Data/binary>>); + _ -> + binary_to_float(Data) + end. + +%% + +-spec to_int(integer() | binary() | list()) -> integer(). + +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). + +set_resp_headers([], Req) -> + Req; +set_resp_headers([{K, V} | T], Req0) -> + Req = cowboy_req:set_resp_header(K, V, Req0), + set_resp_headers(T, Req). + +-spec to_header(iodata() | atom() | number()) -> binary(). + +to_header(Name) -> + Prepared = to_binary(Name), + to_lower(Prepared). + +-spec to_qs(iodata() | atom() | number()) -> binary(). + +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). + +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). + +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). + +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +-spec priv_dir() -> file:filename(). + +priv_dir() -> + {ok, AppName} = application:get_application(), + priv_dir(AppName). + +-spec priv_dir(Application :: atom()) -> file:filename(). + +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +-spec priv_path(Relative :: file:filename()) -> file:filename(). + +priv_path(Relative) -> + filename:join(priv_dir(), Relative). + +-include_lib("kernel/include/file.hrl"). + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. + + +%% + +-spec to_lower(binary()) -> binary(). + +to_lower(S) -> + to_case(lower, S, <<>>). + +-spec to_upper(binary()) -> binary(). + +to_upper(S) -> + to_case(upper, S, <<>>). + +to_case(_Case, <<>>, Acc) -> + Acc; + +to_case(_Case, <>, _Acc) when C > 127 -> + error(badarg); + +to_case(Case = lower, <>, Acc) -> + to_case(Case, Rest, <>); + +to_case(Case = upper, <>, Acc) -> + to_case(Case, Rest, <>). + +to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> + C + 32; +to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> + C + 32; +to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> + C + 32; +to_lower_char(C) -> + C. + +to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> + C - 32; +to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> + C - 32; +to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> + C - 32; +to_upper_char(C) -> + C. diff --git a/samples/server/petstore/flaskConnexion-python2/.swagger-codegen-ignore b/samples/server/petstore/flaskConnexion-python2/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/.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/flaskConnexion-python2/LICENSE b/samples/server/petstore/flaskConnexion-python2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/flaskConnexion-python2/README.md b/samples/server/petstore/flaskConnexion-python2/README.md new file mode 100644 index 00000000000..cfc25505bd7 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/README.md @@ -0,0 +1,28 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled Flask server. + +This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. + +To run the server, please execute the following: + +``` +sudo pip install -U connexion # install Connexion from PyPI +python app.py +``` + +and open your browser to here: + +``` +http://localhost:8080/v2/ui/ +``` + +Your Swagger definition lives here: + +``` +http://localhost:8080/v2/swagger.json +``` + diff --git a/samples/server/petstore/flaskConnexion-python2/__init__.py b/samples/server/petstore/flaskConnexion-python2/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/flaskConnexion-python2/app.py b/samples/server/petstore/flaskConnexion-python2/app.py new file mode 100644 index 00000000000..47814427205 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/app.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python + +import connexion + +if __name__ == '__main__': + app = connexion.App(__name__, specification_dir='./swagger/') + 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) diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/__init__.py b/samples/server/petstore/flaskConnexion-python2/controllers/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py new file mode 100644 index 00000000000..d58d3973ca2 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py @@ -0,0 +1,24 @@ + +def add_pet(body): + return 'do some magic!' + +def delete_pet(petId, apiKey = None): + return 'do some magic!' + +def find_pets_by_status(status): + return 'do some magic!' + +def find_pets_by_tags(tags): + return 'do some magic!' + +def get_pet_by_id(petId): + return 'do some magic!' + +def update_pet(body): + return 'do some magic!' + +def update_pet_with_form(petId, name = None, status = None): + return 'do some magic!' + +def upload_file(petId, additionalMetadata = None, file = None): + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py new file mode 100644 index 00000000000..a25eb40febb --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py @@ -0,0 +1,12 @@ + +def delete_order(orderId): + return 'do some magic!' + +def get_inventory(): + return 'do some magic!' + +def get_order_by_id(orderId): + return 'do some magic!' + +def place_order(body): + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py new file mode 100644 index 00000000000..ec4efef29eb --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py @@ -0,0 +1,24 @@ + +def create_user(body): + return 'do some magic!' + +def create_users_with_array_input(body): + return 'do some magic!' + +def create_users_with_list_input(body): + return 'do some magic!' + +def delete_user(username): + return 'do some magic!' + +def get_user_by_name(username): + return 'do some magic!' + +def login_user(username, password): + return 'do some magic!' + +def logout_user(): + return 'do some magic!' + +def update_user(username, body): + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml new file mode 100644 index 00000000000..7b412611171 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml @@ -0,0 +1,754 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ + \ For this sample, you can use the api key `special-key` to test the authorization\ + \ filters." + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io" +basePath: "/v2" +tags: +- name: "pet" + description: "Everything about your Pets" + externalDocs: + description: "Find out more" + url: "http://swagger.io" +- name: "store" + description: "Access to Petstore orders" +- name: "user" + description: "Operations about user" + externalDocs: + description: "Find out more about our store" + url: "http://swagger.io" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "controllers.pet_controller.add_pet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "controllers.pet_controller.update_pet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + 405: + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma separated strings" + operationId: "controllers.pet_controller.find_pets_by_status" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: true + type: "array" + items: + type: "string" + default: "available" + enum: + - "available" + - "pending" + - "sold" + collectionFormat: "csv" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /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: "controllers.pet_controller.find_pets_by_tags" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: true + type: "array" + items: + type: "string" + collectionFormat: "csv" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a single pet" + operationId: "controllers.pet_controller.get_pet_by_id" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to return" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + x-tags: + - tag: "pet" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "controllers.pet_controller.update_pet_with_form" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "integer" + format: "int64" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "controllers.pet_controller.delete_pet" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "api_key" + in: "header" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "controllers.pet_controller.upload_file" + consumes: + - "multipart/form-data" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/ApiResponse" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "controllers.store_controller.get_inventory" + produces: + - "application/json" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + x-tags: + - tag: "store" + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "controllers.store_controller.place_order" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: true + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + x-tags: + - tag: "store" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "controllers.store_controller.get_order_by_id" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + maximum: 5.0 + minimum: 1.0 + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-tags: + - tag: "store" + 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: "controllers.store_controller.delete_order" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + minimum: 1.0 + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-tags: + - tag: "store" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "controllers.user_controller.create_user" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "controllers.user_controller.create_users_with_array_input" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "controllers.user_controller.create_users_with_list_input" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "controllers.user_controller.login_user" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: true + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + headers: + X-Rate-Limit: + type: "integer" + format: "int32" + description: "calls per hour allowed by the user" + X-Expires-After: + type: "string" + format: "date-time" + description: "date in UTC when toekn expires" + 400: + description: "Invalid username/password supplied" + x-tags: + - tag: "user" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "controllers.user_controller.logout_user" + produces: + - "application/xml" + - "application/json" + parameters: [] + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "controllers.user_controller.get_user_by_name" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-tags: + - tag: "user" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "controllers.user_controller.update_user" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + x-tags: + - tag: "user" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "controllers.user_controller.delete_user" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-tags: + - tag: "user" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + Order: + type: "object" + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + default: false + title: "Pet Order" + description: "An order for a pets from the pet store" + xml: + name: "Order" + Category: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + title: "Pet catehgry" + description: "A category for a pet" + xml: + name: "Category" + User: + type: "object" + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + title: "a User" + description: "A User who is purchasing from the pet store" + xml: + name: "User" + Tag: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + title: "Pet Tag" + description: "A tag for a pet" + xml: + name: "Tag" + Pet: + type: "object" + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + title: "a Pet" + description: "A pet for sale in the pet store" + xml: + name: "Pet" + ApiResponse: + type: "object" + properties: + code: + type: "integer" + format: "int32" + type: + type: "string" + message: + type: "string" + title: "An uploaded response" + description: "Describes the result of uploading an image resource" +externalDocs: + description: "Find out more about Swagger" + url: "http://swagger.io" diff --git a/samples/server/petstore/flaskConnexion/.swagger-codegen-ignore b/samples/server/petstore/flaskConnexion/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/.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/flaskConnexion/LICENSE b/samples/server/petstore/flaskConnexion/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/flaskConnexion/controllers/default_controller.py b/samples/server/petstore/flaskConnexion/controllers/default_controller.py deleted file mode 100644 index e6a231aa6fe..00000000000 --- a/samples/server/petstore/flaskConnexion/controllers/default_controller.py +++ /dev/null @@ -1,60 +0,0 @@ - -def add_pet(body) -> str: - return 'do some magic!' - -def delete_pet(petId, apiKey = None) -> str: - return 'do some magic!' - -def find_pets_by_status(status) -> str: - return 'do some magic!' - -def find_pets_by_tags(tags) -> str: - return 'do some magic!' - -def get_pet_by_id(petId) -> str: - return 'do some magic!' - -def update_pet(body) -> str: - return 'do some magic!' - -def update_pet_with_form(petId, name = None, status = None) -> str: - return 'do some magic!' - -def upload_file(petId, additionalMetadata = None, file = None) -> str: - return 'do some magic!' - -def delete_order(orderId) -> str: - return 'do some magic!' - -def get_inventory() -> str: - return 'do some magic!' - -def get_order_by_id(orderId) -> str: - return 'do some magic!' - -def place_order(body) -> str: - return 'do some magic!' - -def create_user(body) -> str: - return 'do some magic!' - -def create_users_with_array_input(body) -> str: - return 'do some magic!' - -def create_users_with_list_input(body) -> str: - return 'do some magic!' - -def delete_user(username) -> str: - return 'do some magic!' - -def get_user_by_name(username) -> str: - return 'do some magic!' - -def login_user(username, password) -> str: - return 'do some magic!' - -def logout_user() -> str: - return 'do some magic!' - -def update_user(username, body) -> str: - return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py new file mode 100644 index 00000000000..b754758b21e --- /dev/null +++ b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py @@ -0,0 +1,24 @@ + +def add_pet(body) -> str: + return 'do some magic!' + +def delete_pet(petId, apiKey = None) -> str: + return 'do some magic!' + +def find_pets_by_status(status) -> str: + return 'do some magic!' + +def find_pets_by_tags(tags) -> str: + return 'do some magic!' + +def get_pet_by_id(petId) -> str: + return 'do some magic!' + +def update_pet(body) -> str: + return 'do some magic!' + +def update_pet_with_form(petId, name = None, status = None) -> str: + return 'do some magic!' + +def upload_file(petId, additionalMetadata = None, file = None) -> str: + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/controllers/store_controller.py b/samples/server/petstore/flaskConnexion/controllers/store_controller.py new file mode 100644 index 00000000000..5f5d893ff1e --- /dev/null +++ b/samples/server/petstore/flaskConnexion/controllers/store_controller.py @@ -0,0 +1,12 @@ + +def delete_order(orderId) -> str: + return 'do some magic!' + +def get_inventory() -> str: + return 'do some magic!' + +def get_order_by_id(orderId) -> str: + return 'do some magic!' + +def place_order(body) -> str: + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/controllers/user_controller.py b/samples/server/petstore/flaskConnexion/controllers/user_controller.py new file mode 100644 index 00000000000..a040086a508 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/controllers/user_controller.py @@ -0,0 +1,24 @@ + +def create_user(body) -> str: + return 'do some magic!' + +def create_users_with_array_input(body) -> str: + return 'do some magic!' + +def create_users_with_list_input(body) -> str: + return 'do some magic!' + +def delete_user(username) -> str: + return 'do some magic!' + +def get_user_by_name(username) -> str: + return 'do some magic!' + +def login_user(username, password) -> str: + return 'do some magic!' + +def logout_user() -> str: + return 'do some magic!' + +def update_user(username, body) -> str: + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml index 368e2c24e82..7b412611171 100644 --- a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml @@ -37,7 +37,7 @@ paths: - "pet" summary: "Add a new pet to the store" description: "" - operationId: "controllers.default_controller.add_pet" + operationId: "controllers.pet_controller.add_pet" consumes: - "application/json" - "application/xml" @@ -65,7 +65,7 @@ paths: - "pet" summary: "Update an existing pet" description: "" - operationId: "controllers.default_controller.update_pet" + operationId: "controllers.pet_controller.update_pet" consumes: - "application/json" - "application/xml" @@ -98,7 +98,7 @@ paths: - "pet" summary: "Finds Pets by status" description: "Multiple status values can be provided with comma separated strings" - operationId: "controllers.default_controller.find_pets_by_status" + operationId: "controllers.pet_controller.find_pets_by_status" produces: - "application/xml" - "application/json" @@ -138,7 +138,7 @@ paths: summary: "Finds Pets by tags" description: "Multiple tags can be provided with comma separated strings. Use\ \ tag1, tag2, tag3 for testing." - operationId: "controllers.default_controller.find_pets_by_tags" + operationId: "controllers.pet_controller.find_pets_by_tags" produces: - "application/xml" - "application/json" @@ -172,7 +172,7 @@ paths: - "pet" summary: "Find pet by ID" description: "Returns a single pet" - operationId: "controllers.default_controller.get_pet_by_id" + operationId: "controllers.pet_controller.get_pet_by_id" produces: - "application/xml" - "application/json" @@ -201,7 +201,7 @@ paths: - "pet" summary: "Updates a pet in the store with form data" description: "" - operationId: "controllers.default_controller.update_pet_with_form" + operationId: "controllers.pet_controller.update_pet_with_form" consumes: - "application/x-www-form-urlencoded" produces: @@ -238,7 +238,7 @@ paths: - "pet" summary: "Deletes a pet" description: "" - operationId: "controllers.default_controller.delete_pet" + operationId: "controllers.pet_controller.delete_pet" produces: - "application/xml" - "application/json" @@ -268,7 +268,7 @@ paths: - "pet" summary: "uploads an image" description: "" - operationId: "controllers.default_controller.upload_file" + operationId: "controllers.pet_controller.upload_file" consumes: - "multipart/form-data" produces: @@ -307,7 +307,7 @@ paths: - "store" summary: "Returns pet inventories by status" description: "Returns a map of status codes to quantities" - operationId: "controllers.default_controller.get_inventory" + operationId: "controllers.store_controller.get_inventory" produces: - "application/json" parameters: [] @@ -329,7 +329,7 @@ paths: - "store" summary: "Place an order for a pet" description: "" - operationId: "controllers.default_controller.place_order" + operationId: "controllers.store_controller.place_order" produces: - "application/xml" - "application/json" @@ -356,7 +356,7 @@ paths: summary: "Find purchase order by ID" description: "For valid response try integer IDs with value <= 5 or > 10. Other\ \ values will generated exceptions" - operationId: "controllers.default_controller.get_order_by_id" + operationId: "controllers.store_controller.get_order_by_id" produces: - "application/xml" - "application/json" @@ -386,7 +386,7 @@ paths: 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: "controllers.default_controller.delete_order" + operationId: "controllers.store_controller.delete_order" produces: - "application/xml" - "application/json" @@ -410,7 +410,7 @@ paths: - "user" summary: "Create user" description: "This can only be done by the logged in user." - operationId: "controllers.default_controller.create_user" + operationId: "controllers.user_controller.create_user" produces: - "application/xml" - "application/json" @@ -432,7 +432,7 @@ paths: - "user" summary: "Creates list of users with given input array" description: "" - operationId: "controllers.default_controller.create_users_with_array_input" + operationId: "controllers.user_controller.create_users_with_array_input" produces: - "application/xml" - "application/json" @@ -456,7 +456,7 @@ paths: - "user" summary: "Creates list of users with given input array" description: "" - operationId: "controllers.default_controller.create_users_with_list_input" + operationId: "controllers.user_controller.create_users_with_list_input" produces: - "application/xml" - "application/json" @@ -480,7 +480,7 @@ paths: - "user" summary: "Logs user into the system" description: "" - operationId: "controllers.default_controller.login_user" + operationId: "controllers.user_controller.login_user" produces: - "application/xml" - "application/json" @@ -519,7 +519,7 @@ paths: - "user" summary: "Logs out current logged in user session" description: "" - operationId: "controllers.default_controller.logout_user" + operationId: "controllers.user_controller.logout_user" produces: - "application/xml" - "application/json" @@ -535,7 +535,7 @@ paths: - "user" summary: "Get user by user name" description: "" - operationId: "controllers.default_controller.get_user_by_name" + operationId: "controllers.user_controller.get_user_by_name" produces: - "application/xml" - "application/json" @@ -561,7 +561,7 @@ paths: - "user" summary: "Updated user" description: "This can only be done by the logged in user." - operationId: "controllers.default_controller.update_user" + operationId: "controllers.user_controller.update_user" produces: - "application/xml" - "application/json" @@ -589,7 +589,7 @@ paths: - "user" summary: "Delete user" description: "This can only be done by the logged in user." - operationId: "controllers.default_controller.delete_user" + operationId: "controllers.user_controller.delete_user" produces: - "application/xml" - "application/json" @@ -644,6 +644,8 @@ definitions: complete: type: "boolean" default: false + title: "Pet Order" + description: "An order for a pets from the pet store" xml: name: "Order" Category: @@ -654,6 +656,8 @@ definitions: format: "int64" name: type: "string" + title: "Pet catehgry" + description: "A category for a pet" xml: name: "Category" User: @@ -678,6 +682,8 @@ definitions: type: "integer" format: "int32" description: "User Status" + title: "a User" + description: "A User who is purchasing from the pet store" xml: name: "User" Tag: @@ -688,6 +694,8 @@ definitions: format: "int64" name: type: "string" + title: "Pet Tag" + description: "A tag for a pet" xml: name: "Tag" Pet: @@ -725,6 +733,8 @@ definitions: - "available" - "pending" - "sold" + title: "a Pet" + description: "A pet for sale in the pet store" xml: name: "Pet" ApiResponse: @@ -737,6 +747,8 @@ definitions: type: "string" message: type: "string" + title: "An uploaded response" + description: "Describes the result of uploading an image resource" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" diff --git a/samples/server/petstore/go-api-server/.swagger-codegen-ignore b/samples/server/petstore/go-api-server/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/go-api-server/.swagger-codegen-ignore +++ b/samples/server/petstore/go-api-server/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/go-api-server/LICENSE b/samples/server/petstore/go-api-server/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/go-api-server/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/go-api-server/go/README.md b/samples/server/petstore/go-api-server/go/README.md index 62ca0d76901..63bee39fdf0 100644 --- a/samples/server/petstore/go-api-server/go/README.md +++ b/samples/server/petstore/go-api-server/go/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) - API version: 1.0.0 -- Build date: 2016-05-27T09:17:10.992-07:00 +- Build date: 2016-07-20T10:23:02.662-07:00 ### Running the server diff --git a/samples/server/petstore/go-api-server/go/routers.go b/samples/server/petstore/go-api-server/go/routers.go index 8704c12c4bd..c59db1c0f6b 100644 --- a/samples/server/petstore/go-api-server/go/routers.go +++ b/samples/server/petstore/go-api-server/go/routers.go @@ -40,147 +40,147 @@ var routes = Routes{ Route{ "Index", "GET", - "/", + "/v2/", Index, }, Route{ "AddPet", "POST", - "/pet", + "/v2/pet", AddPet, }, Route{ "DeletePet", "DELETE", - "/pet/{petId}", + "/v2/pet/{petId}", DeletePet, }, Route{ "FindPetsByStatus", "GET", - "/pet/findByStatus", + "/v2/pet/findByStatus", FindPetsByStatus, }, Route{ "FindPetsByTags", "GET", - "/pet/findByTags", + "/v2/pet/findByTags", FindPetsByTags, }, Route{ "GetPetById", "GET", - "/pet/{petId}", + "/v2/pet/{petId}", GetPetById, }, Route{ "UpdatePet", "PUT", - "/pet", + "/v2/pet", UpdatePet, }, Route{ "UpdatePetWithForm", "POST", - "/pet/{petId}", + "/v2/pet/{petId}", UpdatePetWithForm, }, Route{ "UploadFile", "POST", - "/pet/{petId}/uploadImage", + "/v2/pet/{petId}/uploadImage", UploadFile, }, Route{ "DeleteOrder", "DELETE", - "/store/order/{orderId}", + "/v2/store/order/{orderId}", DeleteOrder, }, Route{ "GetInventory", "GET", - "/store/inventory", + "/v2/store/inventory", GetInventory, }, Route{ "GetOrderById", "GET", - "/store/order/{orderId}", + "/v2/store/order/{orderId}", GetOrderById, }, Route{ "PlaceOrder", "POST", - "/store/order", + "/v2/store/order", PlaceOrder, }, Route{ "CreateUser", "POST", - "/user", + "/v2/user", CreateUser, }, Route{ "CreateUsersWithArrayInput", "POST", - "/user/createWithArray", + "/v2/user/createWithArray", CreateUsersWithArrayInput, }, Route{ "CreateUsersWithListInput", "POST", - "/user/createWithList", + "/v2/user/createWithList", CreateUsersWithListInput, }, Route{ "DeleteUser", "DELETE", - "/user/{username}", + "/v2/user/{username}", DeleteUser, }, Route{ "GetUserByName", "GET", - "/user/{username}", + "/v2/user/{username}", GetUserByName, }, Route{ "LoginUser", "GET", - "/user/login", + "/v2/user/login", LoginUser, }, Route{ "LogoutUser", "GET", - "/user/logout", + "/v2/user/logout", LogoutUser, }, Route{ "UpdateUser", "PUT", - "/user/{username}", + "/v2/user/{username}", UpdateUser, }, diff --git a/samples/server/petstore/haskell-servant/.swagger-codegen-ignore b/samples/server/petstore/haskell-servant/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/haskell-servant/.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/haskell-servant/LICENSE b/samples/server/petstore/haskell-servant/LICENSE index b0033f5f837..8dada3edaf5 100644 --- a/samples/server/petstore/haskell-servant/LICENSE +++ b/samples/server/petstore/haskell-servant/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -179,7 +178,7 @@ 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 "[]" + 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 @@ -187,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2015 Masahiro Yamauchi + 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. diff --git a/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs new file mode 100644 index 00000000000..75f53f95395 --- /dev/null +++ b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs @@ -0,0 +1,255 @@ +{-# LANGUAGE DataKinds, TypeFamilies, TypeOperators, FlexibleInstances, OverloadedStrings, ViewPatterns #-} +{-# LANGUAGE RecordWildCards, GeneralizedNewtypeDeriving, DeriveTraversable, FlexibleContexts, DeriveGeneric #-} +{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports -fcontext-stack=328 #-} +module SwaggerPetstore.API ( + -- * Client and Server + ServerConfig(..), + SwaggerPetstoreBackend, + createSwaggerPetstoreClient, + runSwaggerPetstoreServer, + runSwaggerPetstoreClient, + runSwaggerPetstoreClientWithManager, + SwaggerPetstoreClient, + -- ** Servant + SwaggerPetstoreAPI, + ) where + +import SwaggerPetstore.Types + +import Data.Aeson (Value) +import Data.Coerce (coerce) +import Servant.API +import Servant (serve, ServantErr) +import Web.HttpApiData +import qualified Network.Wai.Handler.Warp as Warp +import qualified Data.Text as T +import Data.Text (Text) +import Servant.Common.BaseUrl(BaseUrl(..)) +import Servant.Client (ServantError, client, Scheme(Http)) +import Data.Proxy (Proxy(..)) +import Control.Monad.IO.Class +import Data.Function ((&)) +import GHC.Exts (IsString(..)) +import qualified Data.Map as Map +import GHC.Generics (Generic) +import Data.Monoid ((<>)) +import Servant.API.Verbs (Verb, StdMethod(..)) +import Control.Monad.Except (ExceptT) +import Network.HTTP.Client (Manager, newManager, defaultManagerSettings) +import Network.HTTP.Types.Method (methodOptions) + +instance ReflectMethod 'OPTIONS where + reflectMethod _ = methodOptions + + + +data FormUpdatePetWithForm = FormUpdatePetWithForm + { updatePetWithFormName :: Text + , updatePetWithFormStatus :: Text + } deriving (Show, Eq, Generic) + +instance FromFormUrlEncoded FormUpdatePetWithForm where + fromFormUrlEncoded inputs = FormUpdatePetWithForm <$> lookupEither "name" inputs <*> lookupEither "status" inputs +instance ToFormUrlEncoded FormUpdatePetWithForm where + toFormUrlEncoded value = [("name", toQueryParam $ updatePetWithFormName value), ("status", toQueryParam $ updatePetWithFormStatus value)] + +data FormUploadFile = FormUploadFile + { uploadFileAdditionalMetadata :: Text + , uploadFileFile :: FilePath + } deriving (Show, Eq, Generic) + +instance FromFormUrlEncoded FormUploadFile where + fromFormUrlEncoded inputs = FormUploadFile <$> lookupEither "additionalMetadata" inputs <*> lookupEither "file" inputs +instance ToFormUrlEncoded FormUploadFile where + toFormUrlEncoded value = [("additionalMetadata", toQueryParam $ uploadFileAdditionalMetadata value), ("file", toQueryParam $ uploadFileFile value)] + + +-- For the form data code generation. +lookupEither :: FromHttpApiData b => Text -> [(Text, Text)] -> Either Text b +lookupEither key assocs = + case lookup key assocs of + Nothing -> Left $ "Could not find parameter " <> key <> " in form data" + Just value -> parseQueryParam value + +-- | Servant type-level API, generated from the Swagger spec for SwaggerPetstore. +type SwaggerPetstoreAPI + = "pet" :> ReqBody '[JSON] Pet :> Verb 'POST 200 '[JSON] () -- 'addPet' route + :<|> "pet" :> Capture "petId" Integer :> Header "api_key" Text :> Verb 'DELETE 200 '[JSON] () -- 'deletePet' route + :<|> "pet" :> "findByStatus" :> QueryParam "status" (QueryList 'CommaSeparated (Text)) :> Verb 'GET 200 '[JSON] [Pet] -- 'findPetsByStatus' route + :<|> "pet" :> "findByTags" :> QueryParam "tags" (QueryList 'CommaSeparated (Text)) :> Verb 'GET 200 '[JSON] [Pet] -- 'findPetsByTags' route + :<|> "pet" :> Capture "petId" Integer :> Verb 'GET 200 '[JSON] Pet -- 'getPetById' route + :<|> "pet" :> ReqBody '[JSON] Pet :> Verb 'PUT 200 '[JSON] () -- 'updatePet' route + :<|> "pet" :> Capture "petId" Integer :> ReqBody '[FormUrlEncoded] FormUpdatePetWithForm :> Verb 'POST 200 '[JSON] () -- 'updatePetWithForm' route + :<|> "pet" :> Capture "petId" Integer :> "uploadImage" :> ReqBody '[FormUrlEncoded] FormUploadFile :> Verb 'POST 200 '[JSON] ApiResponse -- 'uploadFile' route + :<|> "store" :> "order" :> Capture "orderId" Text :> Verb 'DELETE 200 '[JSON] () -- 'deleteOrder' route + :<|> "store" :> "inventory" :> Verb 'GET 200 '[JSON] (Map.Map String Int) -- 'getInventory' route + :<|> "store" :> "order" :> Capture "orderId" Integer :> Verb 'GET 200 '[JSON] Order -- 'getOrderById' route + :<|> "store" :> "order" :> ReqBody '[JSON] Order :> Verb 'POST 200 '[JSON] Order -- 'placeOrder' route + :<|> "user" :> ReqBody '[JSON] User :> Verb 'POST 200 '[JSON] () -- 'createUser' route + :<|> "user" :> "createWithArray" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] () -- 'createUsersWithArrayInput' route + :<|> "user" :> "createWithList" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] () -- 'createUsersWithListInput' route + :<|> "user" :> Capture "username" Text :> Verb 'DELETE 200 '[JSON] () -- 'deleteUser' route + :<|> "user" :> Capture "username" Text :> Verb 'GET 200 '[JSON] User -- 'getUserByName' route + :<|> "user" :> "login" :> QueryParam "username" Text :> QueryParam "password" Text :> Verb 'GET 200 '[JSON] Text -- 'loginUser' route + :<|> "user" :> "logout" :> Verb 'GET 200 '[JSON] () -- 'logoutUser' route + :<|> "user" :> Capture "username" Text :> ReqBody '[JSON] User :> Verb 'PUT 200 '[JSON] () -- 'updateUser' route + +-- | Server or client configuration, specifying the host and port to query or serve on. +data ServerConfig = ServerConfig { + configHost :: String, -- ^ Hostname to serve on, e.g. "127.0.0.1" + configPort :: Int -- ^ Port to serve on, e.g. 8080 + } deriving (Eq, Ord, Show, Read) + +-- | List of elements parsed from a query. +newtype QueryList (p :: CollectionFormat) a = QueryList { fromQueryList :: [a] } + deriving (Functor, Applicative, Monad, Foldable, Traversable) + +-- | Formats in which a list can be encoded into a HTTP path. +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`. Only for GET params. + +instance FromHttpApiData a => FromHttpApiData (QueryList 'CommaSeparated a) where + parseQueryParam = parseSeparatedQueryList ',' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'TabSeparated a) where + parseQueryParam = parseSeparatedQueryList '\t' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'SpaceSeparated a) where + parseQueryParam = parseSeparatedQueryList ' ' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'PipeSeparated a) where + parseQueryParam = parseSeparatedQueryList '|' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'MultiParamArray a) where + parseQueryParam = error "unimplemented FromHttpApiData for MultiParamArray collection format" + +parseSeparatedQueryList :: FromHttpApiData a => Char -> Text -> Either Text (QueryList p a) +parseSeparatedQueryList char = fmap QueryList . mapM parseQueryParam . T.split (== char) + +instance ToHttpApiData a => ToHttpApiData (QueryList 'CommaSeparated a) where + toQueryParam = formatSeparatedQueryList ',' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'TabSeparated a) where + toQueryParam = formatSeparatedQueryList '\t' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'SpaceSeparated a) where + toQueryParam = formatSeparatedQueryList ' ' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'PipeSeparated a) where + toQueryParam = formatSeparatedQueryList '|' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'MultiParamArray a) where + toQueryParam = error "unimplemented ToHttpApiData for MultiParamArray collection format" + +formatSeparatedQueryList :: ToHttpApiData a => Char -> QueryList p a -> Text +formatSeparatedQueryList char = T.intercalate (T.singleton char) . map toQueryParam . fromQueryList + + +-- | Backend for SwaggerPetstore. +-- The backend can be used both for the client and the server. The client generated from the SwaggerPetstore Swagger spec +-- is a backend that executes actions by sending HTTP requests (see @createSwaggerPetstoreClient@). Alternatively, provided +-- a backend, the API can be served using @runSwaggerPetstoreServer@. +data SwaggerPetstoreBackend m = SwaggerPetstoreBackend { + addPet :: Pet -> m (){- ^ -}, + deletePet :: Integer -> Maybe Text -> m (){- ^ -}, + findPetsByStatus :: Maybe [Text] -> m [Pet]{- ^ Multiple status values can be provided with comma separated strings -}, + findPetsByTags :: Maybe [Text] -> m [Pet]{- ^ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -}, + getPetById :: Integer -> m Pet{- ^ Returns a single pet -}, + updatePet :: Pet -> m (){- ^ -}, + updatePetWithForm :: Integer -> FormUpdatePetWithForm -> m (){- ^ -}, + uploadFile :: Integer -> FormUploadFile -> m ApiResponse{- ^ -}, + deleteOrder :: Text -> m (){- ^ For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -}, + getInventory :: m (Map.Map String Int){- ^ Returns a map of status codes to quantities -}, + getOrderById :: Integer -> m Order{- ^ For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -}, + placeOrder :: Order -> m Order{- ^ -}, + createUser :: User -> m (){- ^ This can only be done by the logged in user. -}, + createUsersWithArrayInput :: [User] -> m (){- ^ -}, + createUsersWithListInput :: [User] -> m (){- ^ -}, + deleteUser :: Text -> m (){- ^ This can only be done by the logged in user. -}, + getUserByName :: Text -> m User{- ^ -}, + loginUser :: Maybe Text -> Maybe Text -> m Text{- ^ -}, + logoutUser :: m (){- ^ -}, + updateUser :: Text -> User -> m (){- ^ This can only be done by the logged in user. -} + } + +newtype SwaggerPetstoreClient a = SwaggerPetstoreClient { runClient :: Manager -> BaseUrl -> ExceptT ServantError IO a } + deriving Functor + +instance Applicative SwaggerPetstoreClient where + pure x = SwaggerPetstoreClient (\_ _ -> pure x) + (SwaggerPetstoreClient f) <*> (SwaggerPetstoreClient x) = SwaggerPetstoreClient (\manager url -> f manager url <*> x manager url) + +instance Monad SwaggerPetstoreClient where + (SwaggerPetstoreClient a) >>= f = SwaggerPetstoreClient (\manager url -> do + value <- a manager url + runClient (f value) manager url) + +instance MonadIO SwaggerPetstoreClient where + liftIO io = SwaggerPetstoreClient (\_ _ -> liftIO io) + +createSwaggerPetstoreClient :: SwaggerPetstoreBackend SwaggerPetstoreClient +createSwaggerPetstoreClient = SwaggerPetstoreBackend{..} + where + ((coerce -> addPet) :<|> + (coerce -> deletePet) :<|> + (coerce -> findPetsByStatus) :<|> + (coerce -> findPetsByTags) :<|> + (coerce -> getPetById) :<|> + (coerce -> updatePet) :<|> + (coerce -> updatePetWithForm) :<|> + (coerce -> uploadFile) :<|> + (coerce -> deleteOrder) :<|> + (coerce -> getInventory) :<|> + (coerce -> getOrderById) :<|> + (coerce -> placeOrder) :<|> + (coerce -> createUser) :<|> + (coerce -> createUsersWithArrayInput) :<|> + (coerce -> createUsersWithListInput) :<|> + (coerce -> deleteUser) :<|> + (coerce -> getUserByName) :<|> + (coerce -> loginUser) :<|> + (coerce -> logoutUser) :<|> + (coerce -> updateUser)) = client (Proxy :: Proxy SwaggerPetstoreAPI) + +-- | Run requests in the SwaggerPetstoreClient monad. +runSwaggerPetstoreClient :: ServerConfig -> SwaggerPetstoreClient a -> ExceptT ServantError IO a +runSwaggerPetstoreClient clientConfig cl = do + manager <- liftIO $ newManager defaultManagerSettings + runSwaggerPetstoreClientWithManager manager clientConfig cl + +-- | Run requests in the SwaggerPetstoreClient monad using a custom manager. +runSwaggerPetstoreClientWithManager :: Manager -> ServerConfig -> SwaggerPetstoreClient a -> ExceptT ServantError IO a +runSwaggerPetstoreClientWithManager manager clientConfig cl = + runClient cl manager $ BaseUrl Http (configHost clientConfig) (configPort clientConfig) "" + +-- | Run the SwaggerPetstore server at the provided host and port. +runSwaggerPetstoreServer :: MonadIO m => ServerConfig -> SwaggerPetstoreBackend (ExceptT ServantErr IO) -> m () +runSwaggerPetstoreServer ServerConfig{..} backend = + liftIO $ Warp.runSettings warpSettings $ serve (Proxy :: Proxy SwaggerPetstoreAPI) (serverFromBackend backend) + + where + warpSettings = Warp.defaultSettings & Warp.setPort configPort & Warp.setHost (fromString configHost) + serverFromBackend SwaggerPetstoreBackend{..} = + (coerce addPet :<|> + coerce deletePet :<|> + coerce findPetsByStatus :<|> + coerce findPetsByTags :<|> + coerce getPetById :<|> + coerce updatePet :<|> + coerce updatePetWithForm :<|> + coerce uploadFile :<|> + coerce deleteOrder :<|> + coerce getInventory :<|> + coerce getOrderById :<|> + coerce placeOrder :<|> + coerce createUser :<|> + coerce createUsersWithArrayInput :<|> + coerce createUsersWithListInput :<|> + coerce deleteUser :<|> + coerce getUserByName :<|> + coerce loginUser :<|> + coerce logoutUser :<|> + coerce updateUser) diff --git a/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs new file mode 100644 index 00000000000..4207fbc90c6 --- /dev/null +++ b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs @@ -0,0 +1,119 @@ +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-} + +module SwaggerPetstore.Types ( + ApiResponse (..), + Category (..), + Order (..), + Pet (..), + Tag (..), + User (..), + ) where + +import Data.List (stripPrefix) +import Data.Maybe (fromMaybe) +import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) +import Data.Aeson.Types (Options(..), defaultOptions) +import Data.Text (Text) +import qualified Data.Text as T +import qualified Data.Map as Map +import GHC.Generics (Generic) +import Data.Function ((&)) + + +-- | +data ApiResponse = ApiResponse + { apiResponseCode :: Int -- ^ + , apiResponseType_ :: Text -- ^ + , apiResponseMessage :: Text -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON ApiResponse where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "apiResponse") +instance ToJSON ApiResponse where + toJSON = genericToJSON (removeFieldLabelPrefix False "apiResponse") + +-- | +data Category = Category + { categoryId :: Integer -- ^ + , categoryName :: Text -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON Category where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "category") +instance ToJSON Category where + toJSON = genericToJSON (removeFieldLabelPrefix False "category") + +-- | +data Order = Order + { orderId :: Integer -- ^ + , orderPetId :: Integer -- ^ + , orderQuantity :: Int -- ^ + , orderShipDate :: Integer -- ^ + , orderStatus :: Text -- ^ Order Status + , orderComplete :: Bool -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON Order where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "order") +instance ToJSON Order where + toJSON = genericToJSON (removeFieldLabelPrefix False "order") + +-- | +data Pet = Pet + { petId :: Integer -- ^ + , petCategory :: Category -- ^ + , petName :: Text -- ^ + , petPhotoUrls :: [Text] -- ^ + , petTags :: [Tag] -- ^ + , petStatus :: Text -- ^ pet status in the store + } deriving (Show, Eq, Generic) + +instance FromJSON Pet where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "pet") +instance ToJSON Pet where + toJSON = genericToJSON (removeFieldLabelPrefix False "pet") + +-- | +data Tag = Tag + { tagId :: Integer -- ^ + , tagName :: Text -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON Tag where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "tag") +instance ToJSON Tag where + toJSON = genericToJSON (removeFieldLabelPrefix False "tag") + +-- | +data User = User + { userId :: Integer -- ^ + , userUsername :: Text -- ^ + , userFirstName :: Text -- ^ + , userLastName :: Text -- ^ + , userEmail :: Text -- ^ + , userPassword :: Text -- ^ + , userPhone :: Text -- ^ + , userUserStatus :: Int -- ^ User Status + } deriving (Show, Eq, Generic) + +instance FromJSON User where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "user") +instance ToJSON User where + toJSON = genericToJSON (removeFieldLabelPrefix False "user") + +-- Remove a field label prefix during JSON parsing. +-- Also perform any replacements for special characters. +removeFieldLabelPrefix :: Bool -> String -> Options +removeFieldLabelPrefix forParsing prefix = + defaultOptions + { fieldLabelModifier = fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix . replaceSpecialChars + } + where + replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) + specialChars = [("#", "'Hash"), ("!", "'Exclamation"), ("&", "'Ampersand"), ("@", "'At"), ("$", "'Dollar"), ("%", "'Percent"), ("*", "'Star"), ("+", "'Plus"), (">=", "'Greater_Than_Or_Equal_To"), ("-", "'Dash"), ("<=", "'Less_Than_Or_Equal_To"), ("!=", "'Greater_Than_Or_Equal_To"), (":", "'Colon"), ("^", "'Caret"), ("|", "'Pipe"), (">", "'GreaterThan"), ("=", "'Equal"), ("<", "'LessThan")] + mkCharReplacement (replaceStr, searchStr) = T.unpack . replacer (T.pack searchStr) (T.pack replaceStr) . T.pack + replacer = if forParsing then flip T.replace else T.replace + + diff --git a/samples/server/petstore/java-inflector/.swagger-codegen-ignore b/samples/server/petstore/java-inflector/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/java-inflector/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/java-inflector/LICENSE b/samples/server/petstore/java-inflector/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/java-inflector/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java new file mode 100644 index 00000000000..337a801a13d --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.handler; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

    + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..9755503f600 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,99 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..87ebd2daa69 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,96 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("className") + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(className, animal.className) && + Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..dfe4c29628d --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,52 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o; + return true; + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..37b5df65826 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,77 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + /** + **/ + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("ArrayArrayNumber") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..706d077179c --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,77 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + /** + **/ + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("ArrayNumber") + public List getArrayNumber() { + return arrayNumber; + } + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..423f536df40 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,121 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..865008e47c8 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + /** + **/ + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("declawed") + public Boolean getDeclawed() { + return declawed; + } + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(declawed, cat.declawed); + } + + @Override + public int hashCode() { + return Objects.hash(declawed); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..ff244e9e5ae --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,96 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..0f4b7b6bd0b --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class Client { + @JsonProperty("client") + private String client = null; + + /** + **/ + public Client client(String client) { + this.client = client; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("client") + public String getClient() { + return client; + } + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..ddc5b138ec5 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + /** + **/ + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("breed") + public String getBreed() { + return breed; + } + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(breed, dog.breed); + } + + @Override + public int hashCode() { + return Objects.hash(breed); + } + + @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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..1e0dc66db47 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,161 @@ +package io.swagger.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; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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 = new ArrayList(); + + /** + **/ + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("just_symbol") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + /** + **/ + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_enum") + public List getArrayEnum() { + return arrayEnum; + } + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(justSymbol, enumArrays.justSymbol) && + Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..ec7f34e4229 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,44 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + + + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + 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/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..02fa4fc2283 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,212 @@ +package io.swagger.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; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + + /** + **/ + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_string") + public EnumStringEnum getEnumString() { + return enumString; + } + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + /** + **/ + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_integer") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + **/ + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_number") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(enumString, enumTest.enumString) && + Objects.equals(enumInteger, enumTest.enumInteger) && + Objects.equals(enumNumber, enumTest.enumNumber); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..7535534538c --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,350 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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 Date date = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + /** + * minimum: 10.0 + * maximum: 100.0 + **/ + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("integer") + public Integer getInteger() { + return integer; + } + public void setInteger(Integer integer) { + this.integer = integer; + } + + /** + * minimum: 20.0 + * maximum: 200.0 + **/ + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("int32") + public Integer getInt32() { + return int32; + } + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + **/ + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("int64") + public Long getInt64() { + return int64; + } + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * minimum: 32.1 + * maximum: 543.2 + **/ + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("number") + public BigDecimal getNumber() { + return number; + } + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * minimum: 54.3 + * maximum: 987.6 + **/ + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("float") + public Float getFloat() { + return _float; + } + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * minimum: 67.8 + * maximum: 123.4 + **/ + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("double") + public Double getDouble() { + return _double; + } + public void setDouble(Double _double) { + this._double = _double; + } + + /** + **/ + public FormatTest string(String string) { + this.string = string; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("string") + public String getString() { + return string; + } + public void setString(String string) { + this.string = string; + } + + /** + **/ + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("byte") + public byte[] getByte() { + return _byte; + } + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + **/ + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("binary") + public byte[] getBinary() { + return binary; + } + public void setBinary(byte[] binary) { + this.binary = binary; + } + + /** + **/ + public FormatTest date(Date date) { + this.date = date; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("date") + public Date getDate() { + return date; + } + public void setDate(Date date) { + this.date = date; + } + + /** + **/ + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public Date getDateTime() { + return dateTime; + } + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + public FormatTest password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(integer, formatTest.integer) && + Objects.equals(int32, formatTest.int32) && + Objects.equals(int64, formatTest.int64) && + Objects.equals(number, formatTest.number) && + Objects.equals(_float, formatTest._float) && + Objects.equals(_double, formatTest._double) && + Objects.equals(string, formatTest.string) && + Objects.equals(_byte, formatTest._byte) && + Objects.equals(binary, formatTest.binary) && + Objects.equals(date, formatTest.date) && + Objects.equals(dateTime, formatTest.dateTime) && + Objects.equals(uuid, formatTest.uuid) && + Objects.equals(password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..990188118de --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,96 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + **/ + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + public void setBar(String bar) { + this.bar = bar; + } + + /** + **/ + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("foo") + public String getFoo() { + return foo; + } + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(bar, hasOnlyReadOnly.bar) && + Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..e3e1a7b8753 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,131 @@ +package io.swagger.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; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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 = new HashMap(); + + /** + **/ + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_map_of_string") + public Map> getMapMapOfString() { + return mapMapOfString; + } + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + /** + **/ + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_enum_string") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..ab28e910981 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,123 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public Date getDateTime() { + return dateTime; + } + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..b669912e402 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,99 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing model name starting with number + **/ + +@ApiModel(description = "Model for testing model name starting with number") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + /** + **/ + public Model200Response PropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("class") + public String getPropertyClass() { + return PropertyClass; + } + public void setPropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(name, _200Response.name) && + Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..d2cf14c4833 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,118 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..b240e33ad2f --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,77 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing reserved words + **/ + +@ApiModel(description = "Model for testing reserved words") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + /** + **/ + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("return") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(_return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..2c1e02dbf3e --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,143 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing model name same as property name + **/ + +@ApiModel(description = "Model for testing model name same as property name") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + /** + **/ + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("snake_case") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + /** + **/ + public Name property(String property) { + this.property = property; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("property") + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } + + /** + **/ + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(name, name.name) && + Objects.equals(snakeCase, name.snakeCase) && + Objects.equals(property, name.property) && + Objects.equals(_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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..33566fcb99c --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + /** + **/ + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("JustNumber") + public BigDecimal getJustNumber() { + return justNumber; + } + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(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(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..55d84c48fff --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,220 @@ +package io.swagger.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.Date; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private Date shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..c1b1942400b --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,223 @@ +package io.swagger.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.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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 = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..8dc882acafc --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,96 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + **/ + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + public void setBar(String bar) { + this.bar = bar; + } + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..5503a673041 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + /** + **/ + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("$special[property.name]") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..26fa90e969e --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,96 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..f6e1584d8b0 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,229 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +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; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(example = "null", value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java new file mode 100644 index 00000000000..752414ff9ce --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java @@ -0,0 +1,44 @@ +package io.swagger.handler; + +import io.swagger.inflector.models.RequestContext; +import io.swagger.inflector.models.ResponseContext; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import java.io.File; +import java.util.List; + +import io.swagger.model.*; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") +public class FakeController { + /** + * Uncomment and implement as you see fit. These operations will map + * Directly to operation calls from the routing logic. Because the inflector + * Code allows you to implement logic incrementally, they are disabled. + **/ + + /* + public ResponseContext testClientModel(RequestContext request , Client body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext testEndpointParameters(RequestContext request , BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext testEnumParameters(RequestContext request , List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java index e05a1ffc1f2..d1bf6b1b589 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java @@ -11,14 +11,14 @@ import io.swagger.model.*; import io.swagger.model.Pet; -import io.swagger.model.ApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-04-15T17:48:04.458+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class PetController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java index cf96ddf68fd..ee1a74508f0 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java @@ -13,11 +13,11 @@ import java.util.Map; import io.swagger.model.Order; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-04-15T17:48:04.458+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class StoreController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java index 4d99da8b342..a5ff27d10ba 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java @@ -13,11 +13,11 @@ import io.swagger.model.User; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-04-15T17:48:04.458+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class UserController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml index 0917da7891b..118ca53356a 100644 --- a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml +++ b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml @@ -1,10 +1,9 @@ --- swagger: "2.0" info: - description: "This is a sample server Petstore server. You can find out more about\ - \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ - \ For this sample, you can use the api key `special-key` to test the authorization\ - \ filters." + 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/" @@ -31,6 +30,221 @@ tags: schemes: - "http" paths: + /fake: + get: + tags: + - "fake" + summary: "To test enum parameters" + operationId: "testEnumParameters" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - name: "enum_form_string_array" + in: "formData" + description: "Form parameter enum test (string array)" + required: false + type: "array" + - name: "enum_form_string" + in: "formData" + description: "Form parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + - name: "enum_header_string_array" + in: "header" + description: "Header parameter enum test (string array)" + required: false + type: "array" + - name: "enum_header_string" + in: "header" + description: "Header parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + - name: "enum_query_string_array" + in: "query" + description: "Query parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + default: "$" + enum: + - ">" + - "$" + - name: "enum_query_string" + in: "query" + description: "Query parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + - name: "enum_query_integer" + in: "query" + description: "Query parameter enum test (double)" + required: false + type: "number" + format: "int32" + enum: + - null + - null + - name: "enum_query_double" + in: "formData" + description: "Query parameter enum test (double)" + required: false + type: "number" + format: "double" + enum: + - null + - null + responses: + 400: + description: "Invalid request" + 404: + description: "Not found" + x-contentType: "application/json" + x-accepts: "application/json" + 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.0 + minimum: 10.0 + - name: "int32" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 200.0 + minimum: 20.0 + format: "int32" + - name: "int64" + in: "formData" + description: "None" + required: false + type: "integer" + format: "int64" + - name: "number" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 543.2 + minimum: 32.1 + - name: "float" + in: "formData" + description: "None" + required: false + type: "number" + maximum: 987.6 + format: "float" + - name: "double" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 123.4 + minimum: 67.8 + format: "double" + - name: "string" + in: "formData" + description: "None" + required: true + type: "string" + pattern: "/[a-z]/i" + - name: "byte" + in: "formData" + description: "None" + required: true + type: "string" + format: "byte" + - name: "binary" + in: "formData" + description: "None" + required: false + type: "string" + format: "binary" + - name: "date" + in: "formData" + description: "None" + required: false + type: "string" + format: "date" + - name: "dateTime" + in: "formData" + description: "None" + required: false + type: "string" + format: "date-time" + - name: "password" + in: "formData" + description: "None" + required: false + type: "string" + maxLength: 64 + minLength: 10 + format: "password" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + security: + - http_basic_test: [] + x-contentType: "application/xml; charset=utf-8" + x-accepts: "application/xml; charset=utf-8,application/json; charset=utf-8" + patch: + tags: + - "fake" + summary: "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" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + x-contentType: "application/json" + x-accepts: "application/json" /pet: post: tags: @@ -618,6 +832,8 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + http_basic_test: + type: "basic" definitions: Order: type: "object" @@ -662,6 +878,7 @@ definitions: id: type: "integer" format: "int64" + x-is-unique: true username: type: "string" firstName: @@ -699,6 +916,7 @@ definitions: id: type: "integer" format: "int64" + x-is-unique: true category: $ref: "#/definitions/Category" name: @@ -737,6 +955,288 @@ definitions: type: "string" message: type: "string" + $special[model.name]: + properties: + $special[property.name]: + type: "integer" + format: "int64" + xml: + name: "$special[model.name]" + Return: + properties: + return: + type: "integer" + format: "int32" + description: "Model for testing reserved words" + xml: + name: "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" + 200_response: + properties: + name: + type: "integer" + format: "int32" + class: + type: "string" + description: "Model for testing model name starting with number" + xml: + name: "Name" + Dog: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + breed: + type: "string" + Cat: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + declawed: + type: "boolean" + Animal: + type: "object" + required: + - "className" + discriminator: "className" + properties: + className: + type: "string" + color: + type: "string" + default: "red" + AnimalFarm: + type: "array" + items: + $ref: "#/definitions/Animal" + format_test: + type: "object" + required: + - "byte" + - "date" + - "number" + - "password" + properties: + integer: + type: "integer" + minimum: 10.0 + maximum: 100.0 + int32: + type: "integer" + format: "int32" + minimum: 20.0 + maximum: 200.0 + 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" + 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 + EnumClass: + type: "string" + enum: + - "_abc" + - "-efg" + - "(xyz)" + default: "-efg" + 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 + AdditionalPropertiesClass: + type: "object" + properties: + map_property: + type: "object" + additionalProperties: + type: "string" + map_of_map_property: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + MixedPropertiesAndAdditionalPropertiesClass: + type: "object" + properties: + uuid: + type: "string" + format: "uuid" + dateTime: + type: "string" + format: "date-time" + map: + type: "object" + additionalProperties: + $ref: "#/definitions/Animal" + List: + type: "object" + properties: + 123-list: + type: "string" + Client: + type: "object" + properties: + client: + type: "string" + ReadOnlyFirst: + type: "object" + properties: + bar: + type: "string" + readOnly: true + baz: + type: "string" + hasOnlyReadOnly: + type: "object" + properties: + bar: + type: "string" + readOnly: true + foo: + type: "string" + readOnly: true + MapTest: + type: "object" + properties: + map_map_of_string: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + map_of_enum_string: + type: "object" + additionalProperties: + type: "string" + enum: + - "UPPER" + - "lower" + ArrayTest: + type: "object" + properties: + array_of_string: + type: "array" + items: + type: "string" + array_array_of_integer: + type: "array" + items: + type: "array" + items: + type: "integer" + format: "int64" + array_array_of_model: + type: "array" + items: + type: "array" + items: + $ref: "#/definitions/ReadOnlyFirst" + NumberOnly: + type: "object" + properties: + JustNumber: + type: "number" + ArrayOfNumberOnly: + type: "object" + properties: + ArrayNumber: + type: "array" + items: + type: "number" + ArrayOfArrayOfNumberOnly: + type: "object" + properties: + ArrayArrayNumber: + type: "array" + items: + type: "array" + items: + type: "number" + EnumArrays: + type: "object" + properties: + just_symbol: + type: "string" + enum: + - ">=" + - "$" + array_enum: + type: "array" + items: + type: "string" + enum: + - "fish" + - "crab" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" diff --git a/samples/server/petstore/jaxrs-cxf-cdi/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-cxf-cdi/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/.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/jaxrs-cxf-cdi/LICENSE b/samples/server/petstore/jaxrs-cxf-cdi/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/jaxrs-cxf-cdi/pom.xml b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml new file mode 100644 index 00000000000..4534f2961ac --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + io.swagger + swagger-jaxrs-cxf-cdi-server + war + swagger-jaxrs-cxf-cdi-server + 1.0.0 + + + + src/main/java + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + 3.0.0 + + false + + + + + + + + + + javax + javaee-api + 7.0 + provided + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + 3.0.2 + provided + + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + [2.8.3,3) + + + + + io.swagger + swagger-annotations + [1.5.3,2) + + + + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..5ef9496d397 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,60 @@ +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +@Path("/v2") +public interface PetApi { + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + Response addPet(Pet body); + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + Response deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey); + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + Response findPetsByStatus(@QueryParam("status") List status); + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + Response findPetsByTags(@QueryParam("tags") List tags); + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + Response getPetById(@PathParam("petId") Long petId); + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + Response updatePet(Pet body); + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + Response updatePetWithForm(@PathParam("petId") Long petId,@Multipart(value = "name", required = false) String name,@Multipart(value = "status", required = false) String status); + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + Response uploadFile(@PathParam("petId") Long petId,@Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, + @Multipart(value = "file" , required = false) Attachment fileDetail); +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java new file mode 100644 index 00000000000..2505bbee827 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java @@ -0,0 +1,29 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") +public interface PetApiService { + public Response addPet(Pet body, SecurityContext securityContext); + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext); + public Response findPetsByStatus(List status, SecurityContext securityContext); + public Response findPetsByTags(List tags, SecurityContext securityContext); + public Response getPetById(Long petId, SecurityContext securityContext); + public Response updatePet(Pet body, SecurityContext securityContext); + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext); + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, Attachment fileDetail, SecurityContext securityContext); +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..0280c8b5d9f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,38 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +@Path("/v2") +public interface StoreApi { + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + Response deleteOrder(@PathParam("orderId") String orderId); + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + Response getInventory(); + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + Response getOrderById(@PathParam("orderId") Long orderId); + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + Response placeOrder(Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java new file mode 100644 index 00000000000..2dc8535c8e5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java @@ -0,0 +1,24 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") +public interface StoreApiService { + public Response deleteOrder(String orderId, SecurityContext securityContext); + public Response getInventory(SecurityContext securityContext); + public Response getOrderById(Long orderId, SecurityContext securityContext); + public Response placeOrder(Order body, SecurityContext securityContext); +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..03112276e5c --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,58 @@ +package io.swagger.api; + +import io.swagger.model.User; +import java.util.List; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +@Path("/v2") +public interface UserApi { + @POST + + + @Produces({ "application/xml", "application/json" }) + Response createUser(User body); + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + Response createUsersWithArrayInput(List body); + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + Response createUsersWithListInput(List body); + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + Response deleteUser(@PathParam("username") String username); + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + Response getUserByName(@PathParam("username") String username); + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password); + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + Response logoutUser(); + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + Response updateUser(@PathParam("username") String username,User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java new file mode 100644 index 00000000000..f8c61f5f0a0 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java @@ -0,0 +1,28 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") +public interface UserApiService { + public Response createUser(User body, SecurityContext securityContext); + public Response createUsersWithArrayInput(List body, SecurityContext securityContext); + public Response createUsersWithListInput(List body, SecurityContext securityContext); + public Response deleteUser(String username, SecurityContext securityContext); + public Response getUserByName(String username, SecurityContext securityContext); + public Response loginUser(String username, String password, SecurityContext securityContext); + public Response logoutUser(SecurityContext securityContext); + public Response updateUser(String username, User body, SecurityContext securityContext); +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..0ab2fc43537 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,70 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Category", propOrder = + { "id", "name" +}) + +@XmlRootElement(name="Category") +public class Category { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="name") + private String name = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public String getName() { + return name; + } + public void setName(String name) { + this.name = 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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..741d70648f1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,83 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "ModelApiResponse", propOrder = + { "code", "type", "message" +}) + +@XmlRootElement(name="ModelApiResponse") +public class ModelApiResponse { + + + @XmlElement(name="code") + private Integer code = null; + + @XmlElement(name="type") + private String type = null; + + @XmlElement(name="message") + private String message = null; + + /** + **/ + + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + /** + **/ + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + /** + **/ + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + @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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..31f84c907f8 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,146 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Order", propOrder = + { "id", "petId", "quantity", "shipDate", "status", "complete" +}) + +@XmlRootElement(name="Order") +public class Order { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="petId") + private Long petId = null; + + @XmlElement(name="quantity") + private Integer quantity = null; + + @XmlElement(name="shipDate") + private java.util.Date shipDate = null; + +@XmlType(name="StatusEnum") +@XmlEnum +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + public static StatusEnum fromValue(String v) { + return valueOf(v); + } +} + + + @XmlElement(name="status") + private StatusEnum status = null; + + @XmlElement(name="complete") + private Boolean complete = false; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + /** + **/ + + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + /** + **/ + + public java.util.Date getShipDate() { + return shipDate; + } + public void setShipDate(java.util.Date shipDate) { + this.shipDate = shipDate; + } + /** + * Order Status + **/ + + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + /** + **/ + + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = 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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..d889d2a19cc --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,150 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Pet", propOrder = + { "id", "category", "name", "photoUrls", "tags", "status" +}) + +@XmlRootElement(name="Pet") +public class Pet { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="category") + private Category category = null; + + @XmlElement(name="name") + private String name = null; + + @XmlElement(name="photoUrls") + private List photoUrls = new ArrayList(); + + @XmlElement(name="tags") + private List tags = new ArrayList(); + +@XmlType(name="StatusEnum") +@XmlEnum +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + public static StatusEnum fromValue(String v) { + return valueOf(v); + } +} + + + @XmlElement(name="status") + private StatusEnum status = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + /** + **/ + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + /** + **/ + + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + /** + **/ + + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + /** + * pet status in the store + **/ + + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = 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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..d2cdaf602af --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,70 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Tag", propOrder = + { "id", "name" +}) + +@XmlRootElement(name="Tag") +public class Tag { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="name") + private String name = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public String getName() { + return name; + } + public void setName(String name) { + this.name = 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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..803cf2b73eb --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,149 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "User", propOrder = + { "id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus" +}) + +@XmlRootElement(name="User") +public class User { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="username") + private String username = null; + + @XmlElement(name="firstName") + private String firstName = null; + + @XmlElement(name="lastName") + private String lastName = null; + + @XmlElement(name="email") + private String email = null; + + @XmlElement(name="password") + private String password = null; + + @XmlElement(name="phone") + private String phone = null; + + @XmlElement(name="userStatus") + private Integer userStatus = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + /** + **/ + + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + /** + **/ + + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + /** + **/ + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + /** + **/ + + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + /** + **/ + + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + /** + * User Status + **/ + + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = 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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..7923a562ad6 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,63 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.util.List; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") +public class PetApiServiceImpl implements PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response findPetsByStatus(List status, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response findPetsByTags(List tags, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, Attachment fileDetail, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..9dfc758effd --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,42 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") +public class StoreApiServiceImpl implements StoreApiService { + @Override + public Response deleteOrder(String orderId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getInventory(SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getOrderById(Long orderId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..cf89da4b47a --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,62 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") +public class UserApiServiceImpl implements UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response loginUser(String username, String password, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/swagger.json b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json new file mode 100644 index 00000000000..f48e38d5cb2 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json @@ -0,0 +1,831 @@ +{ + "swagger" : "2.0", + "info" : { + "description" : "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version" : "1.0.0", + "title" : "Swagger Petstore", + "termsOfService" : "http://swagger.io/terms/", + "contact" : { + "email" : "apiteam@swagger.io" + }, + "license" : { + "name" : "Apache 2.0", + "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host" : "petstore.swagger.io", + "basePath" : "/v2", + "tags" : [ { + "name" : "pet", + "description" : "Everything about your Pets", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "schemes" : [ "http" ], + "paths" : { + "/pet" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "Add a new pet to the store", + "description" : "", + "operationId" : "addPet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "put" : { + "tags" : [ "pet" ], + "summary" : "Update an existing pet", + "description" : "", + "operationId" : "updatePet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/findByStatus" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Finds Pets by status", + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "status", + "in" : "query", + "description" : "Status values that need to be considered for filter", + "required" : true, + "type" : "array", + "items" : { + "type" : "string", + "default" : "available", + "enum" : [ "available", "pending", "sold" ] + }, + "collectionFormat" : "csv" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Pet" + } + } + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/findByTags" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Finds Pets by tags", + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : true, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "csv" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Pet" + } + } + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Find pet by ID", + "description" : "Returns a single pet", + "operationId" : "getPetById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to return", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Pet" + } + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ] + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Updates a pet in the store with form data", + "description" : "", + "operationId" : "updatePetWithForm", + "consumes" : [ "application/x-www-form-urlencoded" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "name" : "name", + "in" : "formData", + "description" : "Updated name of the pet", + "required" : false, + "type" : "string" + }, { + "name" : "status", + "in" : "formData", + "description" : "Updated status of the pet", + "required" : false, + "type" : "string" + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "delete" : { + "tags" : [ "pet" ], + "summary" : "Deletes a pet", + "description" : "", + "operationId" : "deletePet", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "api_key", + "in" : "header", + "required" : false, + "type" : "string" + }, { + "name" : "petId", + "in" : "path", + "description" : "Pet id to delete", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "uploads an image", + "description" : "", + "operationId" : "uploadFile", + "consumes" : [ "multipart/form-data" ], + "produces" : [ "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to update", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "name" : "additionalMetadata", + "in" : "formData", + "description" : "Additional data to pass to server", + "required" : false, + "type" : "string" + }, { + "name" : "file", + "in" : "formData", + "description" : "file to upload", + "required" : false, + "type" : "file" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/ApiResponse" + } + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/store/inventory" : { + "get" : { + "tags" : [ "store" ], + "summary" : "Returns pet inventories by status", + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "produces" : [ "application/json" ], + "parameters" : [ ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "object", + "additionalProperties" : { + "type" : "integer", + "format" : "int32" + } + } + } + }, + "security" : [ { + "api_key" : [ ] + } ] + } + }, + "/store/order" : { + "post" : { + "tags" : [ "store" ], + "summary" : "Place an order for a pet", + "description" : "", + "operationId" : "placeOrder", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "order placed for purchasing the pet", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Order" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid Order" + } + } + } + }, + "/store/order/{orderId}" : { + "get" : { + "tags" : [ "store" ], + "summary" : "Find purchase order by ID", + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId" : "getOrderById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "integer", + "maximum" : 5.0, + "minimum" : 1.0, + "format" : "int64" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + } + }, + "delete" : { + "tags" : [ "store" ], + "summary" : "Delete purchase order by ID", + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "string", + "minimum" : 1.0 + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + } + } + }, + "/user" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Create user", + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Created user object", + "required" : true, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/createWithArray" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "description" : "", + "operationId" : "createUsersWithArrayInput", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/User" + } + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/createWithList" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "description" : "", + "operationId" : "createUsersWithListInput", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/User" + } + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/login" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs user into the system", + "description" : "", + "operationId" : "loginUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : true, + "type" : "string" + }, { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "string" + }, + "headers" : { + "X-Rate-Limit" : { + "type" : "integer", + "format" : "int32", + "description" : "calls per hour allowed by the user" + }, + "X-Expires-After" : { + "type" : "string", + "format" : "date-time", + "description" : "date in UTC when toekn expires" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + } + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "description" : "", + "operationId" : "logoutUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "description" : "", + "operationId" : "getUserByName", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be fetched. Use user1 for testing. ", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/User" + } + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + } + }, + "put" : { + "tags" : [ "user" ], + "summary" : "Updated user", + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "name that need to be deleted", + "required" : true, + "type" : "string" + }, { + "in" : "body", + "name" : "body", + "description" : "Updated user object", + "required" : true, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + } + }, + "delete" : { + "tags" : [ "user" ], + "summary" : "Delete user", + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be deleted", + "required" : true, + "type" : "string" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + } + } + } + }, + "securityDefinitions" : { + "petstore_auth" : { + "type" : "oauth2", + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "flow" : "implicit", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + }, + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" + } + }, + "definitions" : { + "Order" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "petId" : { + "type" : "integer", + "format" : "int64" + }, + "quantity" : { + "type" : "integer", + "format" : "int32" + }, + "shipDate" : { + "type" : "string", + "format" : "date-time" + }, + "status" : { + "type" : "string", + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ] + }, + "complete" : { + "type" : "boolean", + "default" : false + } + }, + "title" : "Pet Order", + "description" : "An order for a pets from the pet store", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet catehgry", + "description" : "A category for a pet", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "type" : "integer", + "format" : "int32", + "description" : "User Status" + } + }, + "title" : "a User", + "description" : "A User who is purchasing from the pet store", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "description" : "A tag for a pet", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "type" : "object", + "required" : [ "name", "photoUrls" ], + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "category" : { + "$ref" : "#/definitions/Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/definitions/Tag" + } + }, + "status" : { + "type" : "string", + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "title" : "a Pet", + "description" : "A pet for sale in the pet store", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "description" : "Describes the result of uploading an image resource" + } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + } +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-cxf/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/.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/jaxrs-cxf/LICENSE b/samples/server/petstore/jaxrs-cxf/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java index a57fbd04d81..9e459c248dd 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.io.InputStream; import java.io.OutputStream; @@ -13,48 +13,48 @@ import org.apache.cxf.jaxrs.ext.multipart.*; -@Path("/") +@Path("/v2") public interface PetApi { @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) - public Response addPet(Pet body); + Response addPet(Pet body); @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) - public Response deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey); + Response deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey); @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) - public Response findPetsByStatus(@QueryParam("status") List status); + Response findPetsByStatus(@QueryParam("status") List status); @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) - public Response findPetsByTags(@QueryParam("tags") List tags); + Response findPetsByTags(@QueryParam("tags") List tags); @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) - public Response getPetById(@PathParam("petId") Long petId); + Response getPetById(@PathParam("petId") Long petId); @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) - public Response updatePet(Pet body); + Response updatePet(Pet body); @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/xml", "application/json" }) - public Response updatePetWithForm(@PathParam("petId") Long petId,@Multipart(value = "name", required = false) String name,@Multipart(value = "status", required = false) String status); + Response updatePetWithForm(@PathParam("petId") Long petId,@Multipart(value = "name", required = false) String name,@Multipart(value = "status", required = false) String status); @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) - public Response uploadFile(@PathParam("petId") Long petId,@Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, + Response uploadFile(@PathParam("petId") Long petId,@Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail); } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java index b7ccabe7d8b..2bdd151ec3f 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java @@ -12,27 +12,27 @@ import org.apache.cxf.jaxrs.ext.multipart.*; -@Path("/") +@Path("/v2") public interface StoreApi { @DELETE @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) - public Response deleteOrder(@PathParam("orderId") String orderId); + Response deleteOrder(@PathParam("orderId") String orderId); @GET @Path("/store/inventory") @Produces({ "application/json" }) - public Response getInventory(); + Response getInventory(); @GET @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) - public Response getOrderById(@PathParam("orderId") Long orderId); + Response getOrderById(@PathParam("orderId") Long orderId); @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) - public Response placeOrder(Order body); + Response placeOrder(Order body); } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java index 8874d96a519..f93523bf947 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java @@ -12,47 +12,47 @@ import org.apache.cxf.jaxrs.ext.multipart.*; -@Path("/") +@Path("/v2") public interface UserApi { @POST @Path("/user") @Produces({ "application/xml", "application/json" }) - public Response createUser(User body); + Response createUser(User body); @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) - public Response createUsersWithArrayInput(List body); + Response createUsersWithArrayInput(List body); @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) - public Response createUsersWithListInput(List body); + Response createUsersWithListInput(List body); @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) - public Response deleteUser(@PathParam("username") String username); + Response deleteUser(@PathParam("username") String username); @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) - public Response getUserByName(@PathParam("username") String username); + Response getUserByName(@PathParam("username") String username); @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) - public Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password); + Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password); @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) - public Response logoutUser(); + Response logoutUser(); @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) - public Response updateUser(@PathParam("username") String username,User body); + Response updateUser(@PathParam("username") String username,User body); } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java deleted file mode 100644 index e6100b2fc6a..00000000000 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.swagger.model; - - - - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = - { "code", "type", "message" -}) - -@XmlRootElement(name="ApiResponse") -public class ApiResponse { - - - private Integer code = null; - - private String type = null; - - private String message = null; - - /** - **/ - - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - /** - **/ - - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - /** - **/ - - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApiResponse {\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 static String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java index 80d4ccbfc40..c84e936b3b4 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java @@ -1,7 +1,6 @@ package io.swagger.model; - - +import io.swagger.annotations.ApiModel; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..950307540f4 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,81 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "ModelApiResponse", propOrder = + { "code", "type", "message" +}) + +@XmlRootElement(name="ModelApiResponse") +public class ModelApiResponse { + + + @XmlElement(name="code") + private Integer code = null; + + @XmlElement(name="type") + private String type = null; + + @XmlElement(name="message") + private String message = null; + + /** + **/ + + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + /** + **/ + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + /** + **/ + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + @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 static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java index 7c6356ec4b5..d3d9ffabfb5 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java @@ -1,7 +1,6 @@ package io.swagger.model; - - +import io.swagger.annotations.ApiModel; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -35,7 +34,7 @@ public class Order { @XmlEnum public enum StatusEnum { - PLACED(String.valueOf(""placed"")), APPROVED(String.valueOf(""approved"")), DELIVERED(String.valueOf(""delivered"")); + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); private String value; @@ -53,6 +52,7 @@ public static StatusEnum fromValue(String v) { } } + @XmlElement(name="status") private StatusEnum status = null; diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java index 52682bcdd0a..3c1adb7d97f 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java @@ -1,12 +1,11 @@ package io.swagger.model; +import io.swagger.annotations.ApiModel; import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - - import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -42,7 +41,7 @@ public class Pet { @XmlEnum public enum StatusEnum { - AVAILABLE(String.valueOf(""available"")), PENDING(String.valueOf(""pending"")), SOLD(String.valueOf(""sold"")); + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); private String value; @@ -60,6 +59,7 @@ public static StatusEnum fromValue(String v) { } } + @XmlElement(name="status") private StatusEnum status = null; diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java index 25927e8d4cb..1eddc2f761f 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java @@ -1,7 +1,6 @@ package io.swagger.model; - - +import io.swagger.annotations.ApiModel; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java index e3e3f234123..f66d1df57e0 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java @@ -1,7 +1,6 @@ package io.swagger.model; - - +import io.swagger.annotations.ApiModel; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml new file mode 100644 index 00000000000..6b0b2318022 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -0,0 +1,265 @@ + + 4.0.0 + io.swagger + swagger-jaxrs-cxf-server + jar + swagger-jaxrs-cxf-server + 1.0.0 + + gen/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + 10 + + 8080 + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + gen/java + + + + + + + + + + + + org.springframework + spring-context + ${springframework-version} + + + org.springframework + spring-context-support + ${springframework-version} + + + org.springframework + spring-web + ${springframework-version} + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + + + + org.apache.cxf + cxf-rt-transports-http + ${cxf-version} + + + + org.apache.cxf + cxf-rt-rs-extension-providers + ${cxf-version} + + + + javax.ws.rs + jsr311-api + 1.1.1 + + + + + org.slf4j + slf4j-api + ${slf4j-version} + + + + + org.slf4j + log4j-over-slf4j + ${slf4j-version} + runtime + + + + org.slf4j + jcl-over-slf4j + ${slf4j-version} + + + + org.slf4j + jul-to-slf4j + ${slf4j-version} + + + + ch.qos.logback + logback-classic + 1.0.9 + runtime + + + + + + + + javax.servlet + servlet-api + ${servlet-api-version} + provided + + + + + org.scala-lang + scala-library + ${scala-version} + + + + org.springframework + spring-test + ${springframework-version} + test + + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf-version} + test + + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + + junit + junit + ${junit-version} + test + + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 9.2.9.v20150224 + 1.19.1 + 1.7.21 + 4.12 + 2.5 + UTF-8 + 3.2.1.RELEASE + 2.7.15 + + 1.2 + 2.2 + 1.5.10 + 2.1.4 + 2.10.4 + 2.3.4 + 2.5 + 1.13 + 2.1 + 2.4.2 + 2.4.2 + 1.0.1 + + 4.8.1 + 1.0.0 + 3.2.1 + 1.6.3 + 2.1.3 + 8.1.11.v20130520 + 3.1.5 + 0.90 + 0.90 + 0 + + + diff --git a/samples/server/petstore/jaxrs-resteasy/default/pom.xml b/samples/server/petstore/jaxrs-resteasy/default/pom.xml index 3fe937dbc9b..0a25c0159b3 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/default/pom.xml @@ -107,7 +107,11 @@ joda-time 2.7 - + + io.swagger + swagger-jaxrs + ${swagger-core-version} + junit junit @@ -145,11 +149,11 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 3.0.11.Final 1.6.3 4.8.1 2.5 - \ No newline at end of file + diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiException.java index 32c1e58df06..7fa61c50d24 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiOriginFilter.java index eeb813c3a22..2dc07362c92 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class ApiOriginFilter implements javax.servlet.Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiResponseMessage.java index a9534f09f5d..33f95878e54 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/JacksonConfig.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/JacksonConfig.java new file mode 100644 index 00000000000..d19c9120fd5 --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/JacksonConfig.java @@ -0,0 +1,47 @@ +package io.swagger.api; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.fasterxml.jackson.datatype.joda.JodaModule; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.ISODateTimeFormat; + +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; +import java.io.IOException; + +@Provider +public class JacksonConfig implements ContextResolver { + private final ObjectMapper objectMapper; + + public JacksonConfig() throws Exception { + + objectMapper = new ObjectMapper() + .setDateFormat(new RFC3339DateFormat()) + .registerModule(new JodaModule() { + { + addSerializer(DateTime.class, new StdSerializer(DateTime.class) { + @Override + public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { + jgen.writeString(ISODateTimeFormat.dateTimeNoMillis().print(value)); + } + }); + addSerializer(LocalDate.class, new StdSerializer(LocalDate.class) { + @Override + public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { + jgen.writeString(ISODateTimeFormat.date().print(value)); + } + }); + + } + }); + } + + public ObjectMapper getContext(Class arg0) { + return objectMapper; + } +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/NotFoundException.java index 6379b2b4499..295109d7fc4 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java index 8b3ec467613..eed5979f59a 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java @@ -22,7 +22,7 @@ @Path("/pet") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApiService.java index 0d3e9bb280a..00fb6122505 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApiService.java @@ -17,7 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/RFC3339DateFormat.java new file mode 100644 index 00000000000..7c9e260509e --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/RFC3339DateFormat.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +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/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java index 2fdc2718271..dcc585fabc2 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java @@ -20,7 +20,7 @@ @Path("/store") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApiService.java index f4b9a5ad692..2174b1b3547 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApiService.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StringUtil.java index 2fb1f82f391..6f4a3dadbbf 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StringUtil.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java index 195e99f1a20..ad69b39c570 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java @@ -20,7 +20,7 @@ @Path("/user") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApiService.java index dc81bf13cb6..5cfa9359e6b 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApiService.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java index 172a2ce4436..a551df116fc 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java @@ -3,11 +3,10 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java index c55816bd394..c8898f86971 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -3,11 +3,10 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") public class ModelApiResponse { private Integer code = null; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java index 3d62d7e86e0..586d4b195b3 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java @@ -3,13 +3,12 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; import java.util.Date; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java index 8fa4e7486d8..685d7ab6ee6 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java @@ -3,15 +3,14 @@ import java.util.Objects; import java.util.ArrayList; 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.model.Category; import io.swagger.model.Tag; import java.util.List; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java index 7018295e7f9..48a6ab94a85 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java @@ -3,11 +3,10 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java index abfecb310fd..e95e76c1b41 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java @@ -3,11 +3,10 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index e191d6bbd95..54ae4b48435 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -3,7 +3,7 @@ import io.swagger.api.PetApiService; import io.swagger.api.impl.PetApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class PetApiServiceFactory { private final static PetApiService service = new PetApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 3f8808798dd..79a403fee06 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -3,7 +3,7 @@ import io.swagger.api.StoreApiService; import io.swagger.api.impl.StoreApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class StoreApiServiceFactory { private final static StoreApiService service = new StoreApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 1efe9e725df..2f1ae542f1b 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -3,7 +3,7 @@ import io.swagger.api.UserApiService; import io.swagger.api.impl.UserApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class UserApiServiceFactory { private final static UserApiService service = new UserApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 7bc1c47236d..86b35a56fce 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -6,8 +6,8 @@ import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import java.util.List; import io.swagger.api.NotFoundException; @@ -17,7 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class PetApiServiceImpl extends PetApiService { @Override public Response addPet(Pet body,SecurityContext securityContext) diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 942bb9cd4f1..e07f88cabc0 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class StoreApiServiceImpl extends StoreApiService { @Override public Response deleteOrder(String orderId,SecurityContext securityContext) diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 23a17f2827e..f7d4e85b680 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:05.980+08:00") + public class UserApiServiceImpl extends UserApiService { @Override public Response createUser(User body,SecurityContext securityContext) diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiException.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiException.class deleted file mode 100644 index 1a5809e0121..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiException.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiOriginFilter.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiOriginFilter.class deleted file mode 100644 index dd4fb4e630e..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiOriginFilter.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiResponseMessage.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiResponseMessage.class deleted file mode 100644 index 965310aed6b..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/ApiResponseMessage.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1$1.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1$1.class deleted file mode 100644 index 82ef0b2dc84..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1$1.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1$2.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1$2.class deleted file mode 100644 index cb642d371b5..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1$2.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1.class deleted file mode 100644 index 841c18a9358..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig$1.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig.class deleted file mode 100644 index e85d8d3ded0..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JacksonConfig.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaDateTimeProvider$JodaDateTimeConverter.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaDateTimeProvider$JodaDateTimeConverter.class deleted file mode 100644 index 7113adb510a..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaDateTimeProvider$JodaDateTimeConverter.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaDateTimeProvider.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaDateTimeProvider.class deleted file mode 100644 index 3bbb134bccb..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaDateTimeProvider.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaLocalDateProvider$JodaLocalDateConverter.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaLocalDateProvider$JodaLocalDateConverter.class deleted file mode 100644 index f6d4a456385..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaLocalDateProvider$JodaLocalDateConverter.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaLocalDateProvider.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaLocalDateProvider.class deleted file mode 100644 index cbd65fbdfa0..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/JodaLocalDateProvider.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/NotFoundException.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/NotFoundException.class deleted file mode 100644 index 5a4a6efb20b..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/NotFoundException.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/PetApi.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/PetApi.class deleted file mode 100644 index d79031aa47a..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/PetApi.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/PetApiService.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/PetApiService.class deleted file mode 100644 index 8b92de3726b..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/PetApiService.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/RestApplication.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/RestApplication.class deleted file mode 100644 index ccb5a878805..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/RestApplication.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StoreApi.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StoreApi.class deleted file mode 100644 index 3ec261898f7..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StoreApi.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StoreApiService.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StoreApiService.class deleted file mode 100644 index 97dc7ec7517..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StoreApiService.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StringUtil.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StringUtil.class deleted file mode 100644 index ef5d2e2e15f..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/StringUtil.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/UserApi.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/UserApi.class deleted file mode 100644 index 0d8e9d98a7f..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/UserApi.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/UserApiService.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/UserApiService.class deleted file mode 100644 index efc4546a763..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/UserApiService.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/PetApiServiceFactory.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/PetApiServiceFactory.class deleted file mode 100644 index 959aad11df0..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/PetApiServiceFactory.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/StoreApiServiceFactory.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/StoreApiServiceFactory.class deleted file mode 100644 index bc1ef570a1d..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/StoreApiServiceFactory.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/UserApiServiceFactory.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/UserApiServiceFactory.class deleted file mode 100644 index df26a6dc422..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/factories/UserApiServiceFactory.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/PetApiServiceImpl.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/PetApiServiceImpl.class deleted file mode 100644 index 45937fc2b85..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/PetApiServiceImpl.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/StoreApiServiceImpl.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/StoreApiServiceImpl.class deleted file mode 100644 index e6ec58a2ea9..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/StoreApiServiceImpl.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/UserApiServiceImpl.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/UserApiServiceImpl.class deleted file mode 100644 index 9fa2e01da72..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/api/impl/UserApiServiceImpl.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Category.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Category.class deleted file mode 100644 index 88f5b8a208b..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Category.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/ModelApiResponse.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/ModelApiResponse.class deleted file mode 100644 index 791cf2bc40c..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/ModelApiResponse.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Order$StatusEnum.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Order$StatusEnum.class deleted file mode 100644 index 464b6e1b696..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Order$StatusEnum.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Order.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Order.class deleted file mode 100644 index 4e5b5a3c6c2..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Order.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Pet$StatusEnum.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Pet$StatusEnum.class deleted file mode 100644 index 259e818d7c2..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Pet$StatusEnum.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Pet.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Pet.class deleted file mode 100644 index fdb8183739f..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Pet.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Tag.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Tag.class deleted file mode 100644 index fbb273fe8e6..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/Tag.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/User.class b/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/User.class deleted file mode 100644 index 303b9109b4e..00000000000 Binary files a/samples/server/petstore/jaxrs-resteasy/joda/build/classes/main/io/swagger/model/User.class and /dev/null differ diff --git a/samples/server/petstore/jaxrs-resteasy/joda/pom.xml b/samples/server/petstore/jaxrs-resteasy/joda/pom.xml index 4b41cab66ac..1bbfb57b242 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/joda/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.swagger - swagger-jaxrs-resteasy-joda + swagger-jaxrs-resteasy-joda-server war - swagger-jaxrs-resteasy-server + swagger-jaxrs-resteasy-joda-server 1.0.0 src/main/java @@ -145,11 +145,11 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 3.0.11.Final 1.6.3 4.8.1 2.5 - + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiException.java index 9614941b59f..7fa61c50d24 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiOriginFilter.java index e3ed722543c..2dc07362c92 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class ApiOriginFilter implements javax.servlet.Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiResponseMessage.java index fcaebb85946..33f95878e54 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JacksonConfig.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JacksonConfig.java index a2360fcc82b..d19c9120fd5 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JacksonConfig.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JacksonConfig.java @@ -20,24 +20,25 @@ public class JacksonConfig implements ContextResolver { public JacksonConfig() throws Exception { - objectMapper = new ObjectMapper(); - objectMapper.registerModule(new JodaModule() { - { - addSerializer(DateTime.class, new StdSerializer(DateTime.class) { - @Override - public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { - jgen.writeString(ISODateTimeFormat.dateTimeNoMillis().print(value)); - } - }); - addSerializer(LocalDate.class, new StdSerializer(LocalDate.class) { - @Override - public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { - jgen.writeString(ISODateTimeFormat.date().print(value)); - } - }); + objectMapper = new ObjectMapper() + .setDateFormat(new RFC3339DateFormat()) + .registerModule(new JodaModule() { + { + addSerializer(DateTime.class, new StdSerializer(DateTime.class) { + @Override + public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { + jgen.writeString(ISODateTimeFormat.dateTimeNoMillis().print(value)); + } + }); + addSerializer(LocalDate.class, new StdSerializer(LocalDate.class) { + @Override + public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { + jgen.writeString(ISODateTimeFormat.date().print(value)); + } + }); - } - }); + } + }); } public ObjectMapper getContext(Class arg0) { diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaDateTimeProvider.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaDateTimeProvider.java index 918d08ac95d..024bc6761d4 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaDateTimeProvider.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaDateTimeProvider.java @@ -15,7 +15,6 @@ public class JodaDateTimeProvider implements ParamConverterProvider { public static class JodaDateTimeConverter implements ParamConverter { - @Override public DateTime fromString(String string) { try { DateTime dateTime = DateTime.parse(string); @@ -26,13 +25,11 @@ public DateTime fromString(String string) { } } - @Override public String toString(DateTime t) { return t.toString(); } } - @Override public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { if (DateTime.class.equals(type)) { return (ParamConverter) new JodaDateTimeConverter(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaLocalDateProvider.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaLocalDateProvider.java index a4298e4f6ea..82a67f1aded 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaLocalDateProvider.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/JodaLocalDateProvider.java @@ -15,7 +15,6 @@ public class JodaLocalDateProvider implements ParamConverterProvider { public static class JodaLocalDateConverter implements ParamConverter { - @Override public LocalDate fromString(String string) { try { LocalDate localDate = LocalDate.parse(string); @@ -26,13 +25,11 @@ public LocalDate fromString(String string) { } } - @Override public String toString(LocalDate t) { return t.toString(); } } - @Override public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { if (LocalDate.class.equals(type)) { return (ParamConverter) new JodaLocalDateConverter(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/NotFoundException.java index ddb41ff1ac0..295109d7fc4 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java index b879a0f1a89..3a52f62afd4 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java @@ -5,8 +5,8 @@ import io.swagger.api.factories.PetApiServiceFactory; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import java.util.List; import io.swagger.api.NotFoundException; @@ -22,7 +22,7 @@ @Path("/pet") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApiService.java index 1902d3d3a8e..5a9683f311e 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApiService.java @@ -6,8 +6,8 @@ import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import java.util.List; import io.swagger.api.NotFoundException; @@ -17,7 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/RFC3339DateFormat.java new file mode 100644 index 00000000000..7c9e260509e --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/RFC3339DateFormat.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +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/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java index 09b8dcc2518..dcc585fabc2 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java @@ -20,7 +20,7 @@ @Path("/store") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApiService.java index 9adc467a735..2174b1b3547 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApiService.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StringUtil.java index 128c83a4abd..6f4a3dadbbf 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StringUtil.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java index 7e6ac878913..ad69b39c570 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java @@ -20,7 +20,7 @@ @Path("/user") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApiService.java index fdbeb37c6b8..5cfa9359e6b 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApiService.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java index 8e4077bf511..e006b146a79 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java @@ -3,11 +3,12 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; + -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java index 96b11ce19e5..731e133f76f 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -3,11 +3,12 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; + -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") public class ModelApiResponse { private Integer code = null; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java index 843d9b91421..471e945eddc 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java @@ -3,13 +3,14 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import org.joda.time.DateTime; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class Order { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java index f367b3e32b6..70063709b9c 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java @@ -3,6 +3,7 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.model.Category; import io.swagger.model.Tag; @@ -11,7 +12,7 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class Pet { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java index 3815af34412..bca8b98e094 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java @@ -3,11 +3,12 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; + -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java index 45464c9de08..080cd7c3d9f 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java @@ -3,11 +3,12 @@ import java.util.Objects; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; + -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index 001606d8e53..54ae4b48435 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -3,7 +3,7 @@ import io.swagger.api.PetApiService; import io.swagger.api.impl.PetApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class PetApiServiceFactory { private final static PetApiService service = new PetApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 3372e08c682..79a403fee06 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -3,7 +3,7 @@ import io.swagger.api.StoreApiService; import io.swagger.api.impl.StoreApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class StoreApiServiceFactory { private final static StoreApiService service = new StoreApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 036ec3bfa9e..2f1ae542f1b 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -3,7 +3,7 @@ import io.swagger.api.UserApiService; import io.swagger.api.impl.UserApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class UserApiServiceFactory { private final static UserApiService service = new UserApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 4e088969fbf..86b35a56fce 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -6,8 +6,8 @@ import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import java.util.List; import io.swagger.api.NotFoundException; @@ -17,7 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class PetApiServiceImpl extends PetApiService { @Override public Response addPet(Pet body,SecurityContext securityContext) diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index d77f7ad19ca..e07f88cabc0 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class StoreApiServiceImpl extends StoreApiService { @Override public Response deleteOrder(String orderId,SecurityContext securityContext) diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index ec3dff01ece..f7d4e85b680 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-07-01T21:32:16.906+08:00") + public class UserApiServiceImpl extends UserApiService { @Override public Response createUser(User body,SecurityContext securityContext) diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java b/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java index d76844d13a5..bb3beaf9f89 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java +++ b/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java @@ -54,7 +54,7 @@ public Response deletePet(@HeaderParam("api_key") String apiKey,@PathParam("petI @Path("/findByStatus") @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read_pets", description = "read your pets") @@ -71,7 +71,7 @@ public Response findPetsByStatus(@QueryParam("status") List status) { @Path("/findByTags") @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read_pets", description = "read your pets") diff --git a/samples/server/petstore/jaxrs-spec/swagger.json b/samples/server/petstore/jaxrs-spec/swagger.json index 5581ce2b405..4524933cd36 100644 --- a/samples/server/petstore/jaxrs-spec/swagger.json +++ b/samples/server/petstore/jaxrs-spec/swagger.json @@ -79,7 +79,7 @@ "get" : { "tags" : [ "pet" ], "summary" : "Finds Pets by status", - "description" : "Multiple status values can be provided with comma seperated strings", + "description" : "Multiple status values can be provided with comma separated strings", "operationId" : "findPetsByStatus", "produces" : [ "application/json", "application/xml" ], "parameters" : [ { @@ -116,7 +116,7 @@ "get" : { "tags" : [ "pet" ], "summary" : "Finds Pets by tags", - "description" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId" : "findPetsByTags", "produces" : [ "application/json", "application/xml" ], "parameters" : [ { diff --git a/samples/server/petstore/jaxrs/jersey1/pom.xml b/samples/server/petstore/jaxrs/jersey1/pom.xml index 59fe2067e6a..c8dd08376a7 100644 --- a/samples/server/petstore/jaxrs/jersey1/pom.xml +++ b/samples/server/petstore/jaxrs/jersey1/pom.xml @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 8080 60000 diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..b5c30dc3d5f --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java @@ -0,0 +1,99 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.FakeApiService; +import io.swagger.api.factories.FakeApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Client; +import java.math.BigDecimal; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/fake") + + +@io.swagger.annotations.Api(description = "the fake API") + +public class FakeApi { + private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Response testClientModel( + @ApiParam(value = "client model" ,required=true) Client body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testClientModel(body,securityContext); + } + @POST + + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response testEndpointParameters( + @ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number, + @ApiParam(value = "None", required=true) @FormParam("double") Double _double, + @ApiParam(value = "None", required=true) @FormParam("pattern_without_delimiter") String patternWithoutDelimiter, + @ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte, + @ApiParam(value = "None") @FormParam("integer") Integer integer, + @ApiParam(value = "None") @FormParam("int32") Integer int32, + @ApiParam(value = "None") @FormParam("int64") Long int64, + @ApiParam(value = "None") @FormParam("float") Float _float, + @ApiParam(value = "None") @FormParam("string") String string, + @ApiParam(value = "None") @FormParam("binary") byte[] binary, + @ApiParam(value = "None") @FormParam("date") Date date, + @ApiParam(value = "None") @FormParam("dateTime") Date dateTime, + @ApiParam(value = "None") @FormParam("password") String password, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,binary,date,dateTime,password,securityContext); + } + @GET + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) + public Response testEnumParameters( + @ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @FormParam("enum_form_string_array") List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java new file mode 100644 index 00000000000..2afb295260b --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java @@ -0,0 +1,31 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Client; +import java.math.BigDecimal; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java index 49792814c5e..f476187ce3f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -1,8 +1,10 @@ package io.swagger.api; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import io.swagger.util.Json; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @@ -11,9 +13,15 @@ @Provider @Produces({MediaType.APPLICATION_JSON}) public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - private static ObjectMapper commonMapper = Json.mapper(); public JacksonJsonProvider() { - super.setMapper(commonMapper); + + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .registerModule(new JodaModule()) + .setDateFormat(new RFC3339DateFormat()); + + setMapper(objectMapper); } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java index 4c0aed9e1a3..ad4a24fd32e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.PetApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; @@ -84,7 +85,7 @@ public Response deletePet( @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) public Response findPetsByStatus( - @ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status, + @ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status, @Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); @@ -159,8 +160,8 @@ public Response updatePet( @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) public Response updatePetWithForm( @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId, - @ApiParam(value = "Updated name of the pet")@FormParam("name") String name, - @ApiParam(value = "Updated status of the pet")@FormParam("status") String status, + @ApiParam(value = "Updated name of the pet") @FormParam("name") String name, + @ApiParam(value = "Updated status of the pet") @FormParam("status") String status, @Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePetWithForm(petId,name,status,securityContext); diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index 5e24c438c38..e09b1dfc203 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -36,6 +36,6 @@ public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java new file mode 100644 index 00000000000..7c9e260509e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java index 91c37506181..6742c34fe3e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.StoreApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java index 5c53e751c4f..b0514bdd4e9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.UserApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + 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) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..de739ed501c --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + 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) { + 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) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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 getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java index 67bc75b3b10..ba1ecfdb2b8 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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 = new ArrayList(); + + 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) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..446649217c8 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,214 @@ +package io.swagger.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; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + + 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; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..7c882eb3fee --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,362 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; + +/** + * 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 Date date = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @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.0 + * maximum: 200.0 + * @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(Date date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..3f5492a2e62 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + 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) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..5a55ab81d68 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..82f447004ee 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,81 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +84,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +110,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..09085fb52dc --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,126 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java index 825fa282b8b..1dfe20badf0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java @@ -2,27 +2,37 @@ 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.Date; - - - - +/** + * Order + */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private Date shipDate = null; + @JsonProperty("shipDate") + private Date shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +44,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +182,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -186,7 +214,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java index 24092cbee25..823d25e05a0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ 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; @@ -10,23 +11,34 @@ 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(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +50,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +195,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -189,7 +227,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..50a2a7e4184 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,88 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java index f26d84e74b2..846812a5031 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java index 5dc291a7889..52c5fff826e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java @@ -2,165 +2,186 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -204,7 +225,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java index 1f60ed6cf4b..5e5532439b7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java @@ -15,7 +15,7 @@ public class Bootstrap extends HttpServlet { public void init(ServletConfig config) throws ServletException { Info info = new Info() .title("Swagger Server") - .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.") + .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: \" \\") .termsOfService("http://swagger.io/terms/") .contact(new Contact() .email("apiteam@swagger.io")) diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java new file mode 100644 index 00000000000..d4f8e013671 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.FakeApiService; +import io.swagger.api.impl.FakeApiServiceImpl; + + +public class FakeApiServiceFactory { + private final static FakeApiService service = new FakeApiServiceImpl(); + + public static FakeApiService getFakeApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java new file mode 100644 index 00000000000..797e51fd001 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -0,0 +1,43 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Client; +import java.math.BigDecimal; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 60f77b123d7..439b49212dd 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -65,7 +65,7 @@ public Response updatePetWithForm(Long petId, String name, String status, Securi return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index 9574bbfbb05..bc2bc84665d 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 8080 60000 diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..40d9a325beb --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java @@ -0,0 +1,97 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.FakeApiService; +import io.swagger.api.factories.FakeApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/fake") + + +@io.swagger.annotations.Api(description = "the fake API") + +public class FakeApi { + private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Response testClientModel(@ApiParam(value = "client model" ,required=true) Client body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testClientModel(body,securityContext); + } + @POST + + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response testEndpointParameters(@ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number +,@ApiParam(value = "None", required=true) @FormParam("double") Double _double +,@ApiParam(value = "None", required=true) @FormParam("pattern_without_delimiter") String patternWithoutDelimiter +,@ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte +,@ApiParam(value = "None") @FormParam("integer") Integer integer +,@ApiParam(value = "None") @FormParam("int32") Integer int32 +,@ApiParam(value = "None") @FormParam("int64") Long int64 +,@ApiParam(value = "None") @FormParam("float") Float _float +,@ApiParam(value = "None") @FormParam("string") String string +,@ApiParam(value = "None") @FormParam("binary") byte[] binary +,@ApiParam(value = "None") @FormParam("date") Date date +,@ApiParam(value = "None") @FormParam("dateTime") Date dateTime +,@ApiParam(value = "None") @FormParam("password") String password +,@ApiParam(value = "None") @FormParam("callback") String paramCallback +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,binary,date,dateTime,password,paramCallback,securityContext); + } + @GET + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) + public Response testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @FormParam("enum_form_string_array") List enumFormStringArray +,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString +,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray +,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString +,@ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray +,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString +,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger +,@ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java new file mode 100644 index 00000000000..88909c904e0 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java @@ -0,0 +1,25 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java index 49792814c5e..f476187ce3f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -1,8 +1,10 @@ package io.swagger.api; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import io.swagger.util.Json; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @@ -11,9 +13,15 @@ @Provider @Produces({MediaType.APPLICATION_JSON}) public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - private static ObjectMapper commonMapper = Json.mapper(); public JacksonJsonProvider() { - super.setMapper(commonMapper); + + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .registerModule(new JodaModule()) + .setDateFormat(new RFC3339DateFormat()); + + setMapper(objectMapper); } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java index 20b70593452..696755a2ba5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -5,10 +5,11 @@ import io.swagger.api.factories.PetApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; @@ -43,7 +44,8 @@ public class PetApi { }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.addPet(body,securityContext); } @@ -59,7 +61,9 @@ public Response addPet(@ApiParam(value = "Pet object that needs to be added to t }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.deletePet(petId,apiKey,securityContext); } @@ -77,7 +81,8 @@ public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @P @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status,@Context SecurityContext securityContext) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); } @@ -95,7 +100,8 @@ public Response findPetsByStatus(@ApiParam(value = "Status values that need to b @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags,@Context SecurityContext securityContext) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByTags(tags,securityContext); } @@ -112,7 +118,8 @@ public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=tr @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId,@Context SecurityContext securityContext) + public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getPetById(petId,securityContext); } @@ -132,7 +139,8 @@ public Response getPetById(@ApiParam(value = "ID of pet to return",required=true @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePet(body,securityContext); } @@ -148,7 +156,10 @@ public Response updatePet(@ApiParam(value = "Pet object that needs to be added t }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status,@Context SecurityContext securityContext) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "Updated name of the pet") @FormParam("name") String name +,@ApiParam(value = "Updated status of the pet") @FormParam("status") String status +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePetWithForm(petId,name,status,securityContext); } @@ -164,10 +175,13 @@ public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) - public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata, - @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@Context SecurityContext securityContext) + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata +, + @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail +,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); + return delegate.uploadFile(petId,additionalMetadata,fileInputStream, fileDetail,securityContext); } } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java index e86ffcf5b85..fdd2296320d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -6,8 +6,8 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; @@ -26,5 +26,5 @@ public abstract class PetApiService { public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java new file mode 100644 index 00000000000..7c9e260509e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java index 7319e0465f0..6c4c40b97cc 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.StoreApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import java.util.Map; import io.swagger.model.Order; @@ -39,7 +40,8 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) - public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.deleteOrder(orderId,securityContext); } @@ -67,7 +69,8 @@ public Response getInventory(@Context SecurityContext securityContext) @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getOrderById(orderId,securityContext); } @@ -80,7 +83,8 @@ public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetch @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body,@Context SecurityContext securityContext) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.placeOrder(body,securityContext); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java index ed3d4e4ead4..3c185f148cb 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.UserApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import io.swagger.model.User; import java.util.List; @@ -37,7 +38,8 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body,@Context SecurityContext securityContext) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUser(body,securityContext); } @@ -48,7 +50,8 @@ public Response createUser(@ApiParam(value = "Created user object" ,required=tru @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); } @@ -59,7 +62,8 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); } @@ -72,7 +76,8 @@ public Response createUsersWithListInput(@ApiParam(value = "List of user object" @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.deleteUser(username,securityContext); } @@ -87,7 +92,8 @@ public Response deleteUser(@ApiParam(value = "The name that needs to be deleted" @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getUserByName(username,securityContext); } @@ -100,7 +106,9 @@ public Response getUserByName(@ApiParam(value = "The name that needs to be fetch @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password,@Context SecurityContext securityContext) + public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username +,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.loginUser(username,password,securityContext); } @@ -124,7 +132,9 @@ public Response logoutUser(@Context SecurityContext securityContext) @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username,@ApiParam(value = "Updated user object" ,required=true) User body,@Context SecurityContext securityContext) + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username +,@ApiParam(value = "Updated user object" ,required=true) User body +,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updateUser(username,body,securityContext); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + 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) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..de739ed501c --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + 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) { + 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) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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 getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java index 67bc75b3b10..ba1ecfdb2b8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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 = new ArrayList(); + + 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) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..446649217c8 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,214 @@ +package io.swagger.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; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + + 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; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..7c882eb3fee --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,362 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; + +/** + * 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 Date date = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @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.0 + * maximum: 200.0 + * @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(Date date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..3f5492a2e62 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + 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) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..5a55ab81d68 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..82f447004ee 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,81 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +84,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +110,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..09085fb52dc --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,126 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java index 825fa282b8b..1dfe20badf0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -2,27 +2,37 @@ 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.Date; - - - - +/** + * Order + */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private Date shipDate = null; + @JsonProperty("shipDate") + private Date shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +44,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +182,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -186,7 +214,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index 24092cbee25..823d25e05a0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ 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; @@ -10,23 +11,34 @@ 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(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +50,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +195,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -189,7 +227,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..50a2a7e4184 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,88 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java index f26d84e74b2..846812a5031 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java index 5dc291a7889..52c5fff826e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java @@ -2,165 +2,186 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -204,7 +225,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java index 1f60ed6cf4b..5e5532439b7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/Bootstrap.java @@ -15,7 +15,7 @@ public class Bootstrap extends HttpServlet { public void init(ServletConfig config) throws ServletException { Info info = new Info() .title("Swagger Server") - .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.") + .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: \" \\") .termsOfService("http://swagger.io/terms/") .contact(new Contact() .email("apiteam@swagger.io")) diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java new file mode 100644 index 00000000000..d4f8e013671 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.FakeApiService; +import io.swagger.api.impl.FakeApiServiceImpl; + + +public class FakeApiServiceFactory { + private final static FakeApiService service = new FakeApiServiceImpl(); + + public static FakeApiService getFakeApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java new file mode 100644 index 00000000000..0c98e320362 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -0,0 +1,37 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 6dacf87d932..6268083801c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -4,8 +4,8 @@ import io.swagger.model.*; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; @@ -55,7 +55,7 @@ public Response updatePetWithForm(Long petId, String name, String status, Securi return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/lumen/.swagger-codegen-ignore b/samples/server/petstore/lumen/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/lumen/.swagger-codegen-ignore +++ b/samples/server/petstore/lumen/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/lumen/app/Console/Kernel.php b/samples/server/petstore/lumen/lib/app/Console/Kernel.php similarity index 100% rename from samples/server/petstore/lumen/app/Console/Kernel.php rename to samples/server/petstore/lumen/lib/app/Console/Kernel.php diff --git a/samples/server/petstore/lumen/app/Exceptions/Handler.php b/samples/server/petstore/lumen/lib/app/Exceptions/Handler.php similarity index 100% rename from samples/server/petstore/lumen/app/Exceptions/Handler.php rename to samples/server/petstore/lumen/lib/app/Exceptions/Handler.php diff --git a/samples/server/petstore/lumen/app/Http/controllers/Controller.php b/samples/server/petstore/lumen/lib/app/Http/Controllers/Controller.php similarity index 100% rename from samples/server/petstore/lumen/app/Http/controllers/Controller.php rename to samples/server/petstore/lumen/lib/app/Http/Controllers/Controller.php diff --git a/samples/server/petstore/lumen/app/Http/controllers/FakeApi.php b/samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php similarity index 75% rename from samples/server/petstore/lumen/app/Http/controllers/FakeApi.php rename to samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php index 11c9e2dc4c4..d249e16dbab 100644 --- a/samples/server/petstore/lumen/app/Http/controllers/FakeApi.php +++ b/samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php @@ -38,6 +38,30 @@ public function __construct() { } + /** + * Operation testClientModel + * + * To test \"client\" model. + * + * + * @return Http response + */ + public function testClientModel() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['body'])) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); + } + $body = $input['body']; + + + return response('How about implementing testClientModel as a PATCH method ?'); + } /** * Operation testEndpointParameters * @@ -76,13 +100,13 @@ public function testEndpointParameters() } $double = $input['double']; - if (!isset($input['string'])) { - throw new \InvalidArgumentException('Missing the required parameter $string when calling testEndpointParameters'); + if (!isset($input['pattern_without_delimiter'])) { + throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } - if (!preg_match("/[a-z]/i", $input['string'])) { - throw new \InvalidArgumentException('invalid value for $string when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + if (!preg_match("/^[A-Z].", $input['pattern_without_delimiter'])) { + throw new \InvalidArgumentException('invalid value for $pattern_without_delimiter when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z]..'); } - $string = $input['string']; + $pattern_without_delimiter = $input['pattern_without_delimiter']; if (!isset($input['byte'])) { throw new \InvalidArgumentException('Missing the required parameter $byte when calling testEndpointParameters'); @@ -112,11 +136,16 @@ public function testEndpointParameters() } $float = $input['float']; + if (!preg_match("/[a-z]/i", $input['string'])) { + throw new \InvalidArgumentException('invalid value for $string when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + } + $string = $input['string']; + $binary = $input['binary']; $date = $input['date']; - $dateTime = $input['dateTime']; + $date_time = $input['date_time']; if (strlen($input['password']) > 64) { throw new \InvalidArgumentException('invalid length for $password when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); @@ -130,14 +159,14 @@ public function testEndpointParameters() return response('How about implementing testEndpointParameters as a POST method ?'); } /** - * Operation testEnumQueryParameters + * Operation testEnumParameters * - * To test enum query parameters. + * To test enum parameters. * * * @return Http response */ - public function testEnumQueryParameters() + public function testEnumParameters() { $input = Request::all(); @@ -145,13 +174,23 @@ public function testEnumQueryParameters() //not path params validation - $enumQueryString = $input['enumQueryString']; + $enum_form_string_array = $input['enum_form_string_array']; + + $enum_form_string = $input['enum_form_string']; + + $enum_header_string_array = $input['enum_header_string_array']; + + $enum_header_string = $input['enum_header_string']; + + $enum_query_string_array = $input['enum_query_string_array']; + + $enum_query_string = $input['enum_query_string']; - $enumQueryInteger = $input['enumQueryInteger']; + $enum_query_integer = $input['enum_query_integer']; - $enumQueryDouble = $input['enumQueryDouble']; + $enum_query_double = $input['enum_query_double']; - return response('How about implementing testEnumQueryParameters as a GET method ?'); + return response('How about implementing testEnumParameters as a GET method ?'); } } diff --git a/samples/server/petstore/lumen/app/Http/controllers/PetApi.php b/samples/server/petstore/lumen/lib/app/Http/Controllers/PetApi.php similarity index 92% rename from samples/server/petstore/lumen/app/Http/controllers/PetApi.php rename to samples/server/petstore/lumen/lib/app/Http/Controllers/PetApi.php index bd06e75fa6e..107f8892bf6 100644 --- a/samples/server/petstore/lumen/app/Http/controllers/PetApi.php +++ b/samples/server/petstore/lumen/lib/app/Http/Controllers/PetApi.php @@ -139,11 +139,11 @@ public function findPetsByTags() * * Deletes a pet. * - * @param Long $petId Pet id to delete (required) + * @param int $pet_id Pet id to delete (required) * * @return Http response */ - public function deletePet($petId) + public function deletePet($pet_id) { $input = Request::all(); @@ -159,11 +159,11 @@ public function deletePet($petId) * * Find pet by ID. * - * @param Long $petId ID of pet to return (required) + * @param int $pet_id ID of pet to return (required) * * @return Http response */ - public function getPetById($petId) + public function getPetById($pet_id) { $input = Request::all(); @@ -179,11 +179,11 @@ public function getPetById($petId) * * Updates a pet in the store with form data. * - * @param Long $petId ID of pet that needs to be updated (required) + * @param int $pet_id ID of pet that needs to be updated (required) * * @return Http response */ - public function updatePetWithForm($petId) + public function updatePetWithForm($pet_id) { $input = Request::all(); @@ -199,11 +199,11 @@ public function updatePetWithForm($petId) * * uploads an image. * - * @param Long $petId ID of pet to update (required) + * @param int $pet_id ID of pet to update (required) * * @return Http response */ - public function uploadFile($petId) + public function uploadFile($pet_id) { $input = Request::all(); diff --git a/samples/server/petstore/lumen/app/Http/controllers/StoreApi.php b/samples/server/petstore/lumen/lib/app/Http/Controllers/StoreApi.php similarity index 84% rename from samples/server/petstore/lumen/app/Http/controllers/StoreApi.php rename to samples/server/petstore/lumen/lib/app/Http/Controllers/StoreApi.php index 4eae1e17c9f..24cd6936225 100644 --- a/samples/server/petstore/lumen/app/Http/controllers/StoreApi.php +++ b/samples/server/petstore/lumen/lib/app/Http/Controllers/StoreApi.php @@ -86,17 +86,17 @@ public function placeOrder() * * Delete purchase order by ID. * - * @param String $orderId ID of the order that needs to be deleted (required) + * @param string $order_id ID of the order that needs to be deleted (required) * * @return Http response */ - public function deleteOrder($orderId) + public function deleteOrder($order_id) { $input = Request::all(); //path params validation - if ($orderId] < 1.0) { - throw new \InvalidArgumentException('invalid value for $orderId when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); + if ($order_id] < 1.0) { + throw new \InvalidArgumentException('invalid value for $order_id when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); } @@ -109,20 +109,20 @@ public function deleteOrder($orderId) * * Find purchase order by ID. * - * @param Long $orderId ID of pet that needs to be fetched (required) + * @param int $order_id ID of pet that needs to be fetched (required) * * @return Http response */ - public function getOrderById($orderId) + public function getOrderById($order_id) { $input = Request::all(); //path params validation - if ($orderId] > 5.0) { - throw new \InvalidArgumentException('invalid value for $orderId when calling StoreApi.getOrderById, must be smaller than or equal to 5.0.'); + if ($order_id] > 5.0) { + throw new \InvalidArgumentException('invalid value for $order_id when calling StoreApi.getOrderById, must be smaller than or equal to 5.0.'); } - if ($orderId] < 1.0) { - throw new \InvalidArgumentException('invalid value for $orderId when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); + if ($order_id] < 1.0) { + throw new \InvalidArgumentException('invalid value for $order_id when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); } diff --git a/samples/server/petstore/lumen/app/Http/controllers/UserApi.php b/samples/server/petstore/lumen/lib/app/Http/Controllers/UserApi.php similarity index 96% rename from samples/server/petstore/lumen/app/Http/controllers/UserApi.php rename to samples/server/petstore/lumen/lib/app/Http/Controllers/UserApi.php index 331c90525e9..92869eddab4 100644 --- a/samples/server/petstore/lumen/app/Http/controllers/UserApi.php +++ b/samples/server/petstore/lumen/lib/app/Http/Controllers/UserApi.php @@ -163,7 +163,7 @@ public function logoutUser() * * Delete user. * - * @param String $username The name that needs to be deleted (required) + * @param string $username The name that needs to be deleted (required) * * @return Http response */ @@ -183,7 +183,7 @@ public function deleteUser($username) * * Get user by user name. * - * @param String $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * * @return Http response */ @@ -203,7 +203,7 @@ public function getUserByName($username) * * Updated user. * - * @param String $username name that need to be deleted (required) + * @param string $username name that need to be deleted (required) * * @return Http response */ diff --git a/samples/server/petstore/lumen/app/Http/Middleware/Authenticate.php b/samples/server/petstore/lumen/lib/app/Http/Middleware/Authenticate.php similarity index 100% rename from samples/server/petstore/lumen/app/Http/Middleware/Authenticate.php rename to samples/server/petstore/lumen/lib/app/Http/Middleware/Authenticate.php diff --git a/samples/server/petstore/lumen/app/Http/routes.php b/samples/server/petstore/lumen/lib/app/Http/routes.php similarity index 75% rename from samples/server/petstore/lumen/app/Http/routes.php rename to samples/server/petstore/lumen/lib/app/Http/routes.php index c61d6d3c4d3..70feeed6b6d 100644 --- a/samples/server/petstore/lumen/app/Http/routes.php +++ b/samples/server/petstore/lumen/lib/app/Http/routes.php @@ -33,158 +33,165 @@ return $app->version(); }); +/** + * PATCH testClientModel + * Summary: To test \"client\" model + * Notes: + * Output-Formats: [application/json] + */ +$app->PATCH('/v2/fake', 'FakeApi@testClientModel'); /** * POST testEndpointParameters * Summary: Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Notes: Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Output-Formats: [application/xml; charset=utf-8, application/json; charset=utf-8] */ -$app->POST('/fake', 'FakeApi@testEndpointParameters'); +$app->POST('/v2/fake', 'FakeApi@testEndpointParameters'); /** - * GET testEnumQueryParameters - * Summary: To test enum query parameters + * GET testEnumParameters + * Summary: To test enum parameters * Notes: * Output-Formats: [application/json] */ -$app->GET('/fake', 'FakeApi@testEnumQueryParameters'); +$app->GET('/v2/fake', 'FakeApi@testEnumParameters'); /** * POST addPet * Summary: Add a new pet to the store * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet', 'PetApi@addPet'); +$app->POST('/v2/pet', 'PetApi@addPet'); /** * PUT updatePet * Summary: Update an existing pet * Notes: * Output-Formats: [application/xml, application/json] */ -$app->PUT('/pet', 'PetApi@updatePet'); +$app->PUT('/v2/pet', 'PetApi@updatePet'); /** * GET findPetsByStatus * Summary: Finds Pets by status * Notes: Multiple status values can be provided with comma separated strings * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByStatus', 'PetApi@findPetsByStatus'); +$app->GET('/v2/pet/findByStatus', 'PetApi@findPetsByStatus'); /** * GET findPetsByTags * Summary: Finds Pets by tags * Notes: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByTags', 'PetApi@findPetsByTags'); +$app->GET('/v2/pet/findByTags', 'PetApi@findPetsByTags'); /** * DELETE deletePet * Summary: Deletes a pet * Notes: * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/pet/{petId}', 'PetApi@deletePet'); +$app->DELETE('/v2/pet/{petId}', 'PetApi@deletePet'); /** * GET getPetById * Summary: Find pet by ID * Notes: Returns a single pet * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/{petId}', 'PetApi@getPetById'); +$app->GET('/v2/pet/{petId}', 'PetApi@getPetById'); /** * POST updatePetWithForm * Summary: Updates a pet in the store with form data * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet/{petId}', 'PetApi@updatePetWithForm'); +$app->POST('/v2/pet/{petId}', 'PetApi@updatePetWithForm'); /** * POST uploadFile * Summary: uploads an image * Notes: * Output-Formats: [application/json] */ -$app->POST('/pet/{petId}/uploadImage', 'PetApi@uploadFile'); +$app->POST('/v2/pet/{petId}/uploadImage', 'PetApi@uploadFile'); /** * GET getInventory * Summary: Returns pet inventories by status * Notes: Returns a map of status codes to quantities * Output-Formats: [application/json] */ -$app->GET('/store/inventory', 'StoreApi@getInventory'); +$app->GET('/v2/store/inventory', 'StoreApi@getInventory'); /** * POST placeOrder * Summary: Place an order for a pet * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/store/order', 'StoreApi@placeOrder'); +$app->POST('/v2/store/order', 'StoreApi@placeOrder'); /** * DELETE deleteOrder * Summary: Delete purchase order by ID * Notes: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/store/order/{orderId}', 'StoreApi@deleteOrder'); +$app->DELETE('/v2/store/order/{orderId}', 'StoreApi@deleteOrder'); /** * GET getOrderById * Summary: Find purchase order by ID * Notes: For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Output-Formats: [application/xml, application/json] */ -$app->GET('/store/order/{orderId}', 'StoreApi@getOrderById'); +$app->GET('/v2/store/order/{orderId}', 'StoreApi@getOrderById'); /** * POST createUser * Summary: Create user * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->POST('/user', 'UserApi@createUser'); +$app->POST('/v2/user', 'UserApi@createUser'); /** * POST createUsersWithArrayInput * Summary: Creates list of users with given input array * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithArray', 'UserApi@createUsersWithArrayInput'); +$app->POST('/v2/user/createWithArray', 'UserApi@createUsersWithArrayInput'); /** * POST createUsersWithListInput * Summary: Creates list of users with given input array * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithList', 'UserApi@createUsersWithListInput'); +$app->POST('/v2/user/createWithList', 'UserApi@createUsersWithListInput'); /** * GET loginUser * Summary: Logs user into the system * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/login', 'UserApi@loginUser'); +$app->GET('/v2/user/login', 'UserApi@loginUser'); /** * GET logoutUser * Summary: Logs out current logged in user session * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/logout', 'UserApi@logoutUser'); +$app->GET('/v2/user/logout', 'UserApi@logoutUser'); /** * DELETE deleteUser * Summary: Delete user * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/user/{username}', 'UserApi@deleteUser'); +$app->DELETE('/v2/user/{username}', 'UserApi@deleteUser'); /** * GET getUserByName * Summary: Get user by user name * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/{username}', 'UserApi@getUserByName'); +$app->GET('/v2/user/{username}', 'UserApi@getUserByName'); /** * PUT updateUser * Summary: Updated user * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->PUT('/user/{username}', 'UserApi@updateUser'); +$app->PUT('/v2/user/{username}', 'UserApi@updateUser'); diff --git a/samples/server/petstore/lumen/app/User.php b/samples/server/petstore/lumen/lib/app/User.php similarity index 100% rename from samples/server/petstore/lumen/app/User.php rename to samples/server/petstore/lumen/lib/app/User.php diff --git a/samples/server/petstore/lumen/bootstrap/app.php b/samples/server/petstore/lumen/lib/bootstrap/app.php similarity index 100% rename from samples/server/petstore/lumen/bootstrap/app.php rename to samples/server/petstore/lumen/lib/bootstrap/app.php diff --git a/samples/server/petstore/lumen/composer.json b/samples/server/petstore/lumen/lib/composer.json similarity index 100% rename from samples/server/petstore/lumen/composer.json rename to samples/server/petstore/lumen/lib/composer.json diff --git a/samples/server/petstore/lumen/public/index.php b/samples/server/petstore/lumen/lib/public/index.php similarity index 100% rename from samples/server/petstore/lumen/public/index.php rename to samples/server/petstore/lumen/lib/public/index.php diff --git a/samples/server/petstore/lumen/readme.md b/samples/server/petstore/lumen/lib/readme.md similarity index 100% rename from samples/server/petstore/lumen/readme.md rename to samples/server/petstore/lumen/lib/readme.md diff --git a/samples/server/petstore/nancyfx/.swagger-codegen-ignore b/samples/server/petstore/nancyfx/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/nancyfx/.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/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index 896f0bd86f6..0a38b2ea778 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", "{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{D198220E-91F6-402F-966F-8EF6105B1B75}" 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 -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Debug|Any CPU.Build.0 = Debug|Any CPU -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Release|Any CPU.ActiveCfg = Release|Any CPU -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Release|Any CPU.Build.0 = Release|Any CPU +{D198220E-91F6-402F-966F-8EF6105B1B75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{D198220E-91F6-402F-966F-8EF6105B1B75}.Debug|Any CPU.Build.0 = Debug|Any CPU +{D198220E-91F6-402F-966F-8EF6105B1B75}.Release|Any CPU.ActiveCfg = Release|Any CPU +{D198220E-91F6-402F-966F-8EF6105B1B75}.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/LICENSE b/samples/server/petstore/nancyfx/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/nancyfx/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index 46fb435d419..1d18142a14a 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,11 +3,11 @@ Debug AnyCPU - {1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353} + {D198220E-91F6-402F-966F-8EF6105B1B75} Library Properties IO.Swagger.v2 - + IO.Swagger v4.5 512 @@ -39,8 +39,8 @@ ..\..\packages\NodaTime.1.3.1\lib\net35-Client\NodaTime.dll True - - ..\..\packages\Sharpility.1.2.1\lib\net45\Sharpility.dll + + ..\..\packages\Sharpility.1.2.2\lib\net45\Sharpility.dll True diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec index f6ab1af8e9b..889fe96ab03 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec @@ -8,7 +8,7 @@ swagger-codegen false NancyFx IO.Swagger API - http://helloreverb.com/terms/ + 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/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/ApiResponse.cs new file mode 100644 index 00000000000..8eb40938412 --- /dev/null +++ b/samples/server/petstore/nancyfx/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 +{ + /// + /// ApiResponse + /// + 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() + { + } + } + + + } +} diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs index 22245ee5bfe..7404b483830 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs @@ -155,6 +155,7 @@ internal OrderBuilder() private void SetupDefaults() { + _Complete = false; } /// diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs index f3ab9ee2892..d6922531e24 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs @@ -9,6 +9,16 @@ 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. @@ -24,8 +34,10 @@ public PetModule(PetService service) : base("/v2") Post["/pet"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'"); + service.AddPet(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Delete["/pet/{petId}"] = parameters => @@ -35,18 +47,22 @@ public PetModule(PetService service) : base("/v2") Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'"); service.DeletePet(Context, petId, apiKey); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Get["/pet/findByStatus"] = parameters => { - var status = Parameters.ValueOf>(parameters, Context.Request, "status", ParameterType.Query); + var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); + Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); + return service.FindPetsByStatus(Context, status); }; Get["/pet/findByTags"] = parameters => { var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); + Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); + return service.FindPetsByTags(Context, tags); }; @@ -61,19 +77,21 @@ public PetModule(PetService service) : base("/v2") Put["/pet"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'"); + service.UpdatePet(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/pet/{petId}"] = parameters => { - var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + 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'"); service.UpdatePetWithForm(Context, petId, name, status); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/pet/{petId}/uploadImage"] = parameters => @@ -83,8 +101,7 @@ public PetModule(PetService service) : base("/v2") var file = Parameters.ValueOf(parameters, Context.Request, "file", ParameterType.Undefined); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'"); - service.UploadFile(Context, petId, additionalMetadata, file); - return new Response { ContentType = "application/json"}; + return service.UploadFile(Context, petId, additionalMetadata, file); }; } } @@ -98,7 +115,7 @@ public interface PetService /// /// /// Context of request - /// Pet object that needs to be added to the store (optional) + /// Pet object that needs to be added to the store /// void AddPet(NancyContext context, Pet body); @@ -112,26 +129,26 @@ public interface PetService void DeletePet(NancyContext context, long? petId, string apiKey); /// - /// Multiple status values can be provided with comma seperated strings + /// Multiple status values can be provided with comma separated strings /// /// Context of request - /// Status values that need to be considered for filter (optional, default to available) + /// Status values that need to be considered for filter /// List<Pet> - List FindPetsByStatus(NancyContext context, List status); + List FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); /// - /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// Context of request - /// Tags to filter by (optional) + /// Tags to filter by /// List<Pet> List FindPetsByTags(NancyContext context, List tags); /// - /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// Returns a single pet /// /// Context of request - /// ID of pet that needs to be fetched + /// ID of pet to return /// Pet Pet GetPetById(NancyContext context, long? petId); @@ -139,7 +156,7 @@ public interface PetService /// /// /// Context of request - /// Pet object that needs to be added to the store (optional) + /// Pet object that needs to be added to the store /// void UpdatePet(NancyContext context, Pet body); @@ -151,7 +168,7 @@ public interface PetService /// Updated name of the pet (optional) /// Updated status of the pet (optional) /// - void UpdatePetWithForm(NancyContext context, string petId, string name, string status); + void UpdatePetWithForm(NancyContext context, long? petId, string name, string status); /// /// @@ -160,8 +177,8 @@ public interface PetService /// ID of pet to update /// Additional data to pass to server (optional) /// file to upload (optional) - /// - void UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); + /// ApiResponse + ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); } /// @@ -179,7 +196,7 @@ public virtual void DeletePet(NancyContext context, long? petId, string apiKey) DeletePet(petId, apiKey); } - public virtual List FindPetsByStatus(NancyContext context, List status) + public virtual List FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) { return FindPetsByStatus(status); } @@ -199,21 +216,21 @@ public virtual void UpdatePet(NancyContext context, Pet body) UpdatePet(body); } - public virtual void UpdatePetWithForm(NancyContext context, string petId, string name, string status) + public virtual void UpdatePetWithForm(NancyContext context, long? petId, string name, string status) { UpdatePetWithForm(petId, name, status); } - public virtual void UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) + public virtual ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) { - UploadFile(petId, additionalMetadata, file); + return UploadFile(petId, additionalMetadata, file); } protected abstract void AddPet(Pet body); protected abstract void DeletePet(long? petId, string apiKey); - protected abstract List FindPetsByStatus(List status); + protected abstract List FindPetsByStatus(FindPetsByStatusStatusEnum? status); protected abstract List FindPetsByTags(List tags); @@ -221,9 +238,9 @@ public virtual void UploadFile(NancyContext context, long? petId, string additio protected abstract void UpdatePet(Pet body); - protected abstract void UpdatePetWithForm(string petId, string name, string status); + protected abstract void UpdatePetWithForm(long? petId, string name, string status); - protected abstract void UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); + protected abstract ApiResponse UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); } } diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs index 06f397db408..e5eed7a2485 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs @@ -27,7 +27,7 @@ public StoreModule(StoreService service) : base("/v2") Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'DeleteOrder'"); service.DeleteOrder(Context, orderId); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Get["/store/inventory"] = parameters => @@ -38,7 +38,7 @@ public StoreModule(StoreService service) : base("/v2") Get["/store/order/{orderId}"] = parameters => { - var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); + var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'GetOrderById'"); return service.GetOrderById(Context, orderId); @@ -47,6 +47,8 @@ public StoreModule(StoreService service) : base("/v2") Post["/store/order"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'PlaceOrder'"); + return service.PlaceOrder(Context, body); }; } @@ -78,13 +80,13 @@ public interface StoreService /// Context of request /// ID of pet that needs to be fetched /// Order - Order GetOrderById(NancyContext context, string orderId); + Order GetOrderById(NancyContext context, long? orderId); /// /// /// /// Context of request - /// order placed for purchasing the pet (optional) + /// order placed for purchasing the pet /// Order Order PlaceOrder(NancyContext context, Order body); } @@ -104,7 +106,7 @@ public virtual void DeleteOrder(NancyContext context, string orderId) return GetInventory(); } - public virtual Order GetOrderById(NancyContext context, string orderId) + public virtual Order GetOrderById(NancyContext context, long? orderId) { return GetOrderById(orderId); } @@ -118,7 +120,7 @@ public virtual Order PlaceOrder(NancyContext context, Order body) protected abstract Dictionary GetInventory(); - protected abstract Order GetOrderById(string orderId); + protected abstract Order GetOrderById(long? orderId); protected abstract Order PlaceOrder(Order body); } diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs index 8350479ef12..978013f17bb 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs @@ -24,22 +24,28 @@ public UserModule(UserService service) : base("/v2") Post["/user"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUser'"); + service.CreateUser(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/user/createWithArray"] = parameters => { var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithArrayInput'"); + service.CreateUsersWithArrayInput(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/user/createWithList"] = parameters => { var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithListInput'"); + service.CreateUsersWithListInput(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Delete["/user/{username}"] = parameters => @@ -48,7 +54,7 @@ public UserModule(UserService service) : base("/v2") Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'DeleteUser'"); service.DeleteUser(Context, username); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Get["/user/{username}"] = parameters => @@ -63,6 +69,10 @@ public UserModule(UserService service) : base("/v2") { 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 service.LoginUser(Context, username, password); }; @@ -70,7 +80,7 @@ public UserModule(UserService service) : base("/v2") { service.LogoutUser(Context); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Put["/user/{username}"] = parameters => @@ -79,8 +89,10 @@ public UserModule(UserService service) : base("/v2") var body = this.Bind(); Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'UpdateUser'"); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdateUser'"); + service.UpdateUser(Context, username, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; } } @@ -94,7 +106,7 @@ public interface UserService /// This can only be done by the logged in user. /// /// Context of request - /// Created user object (optional) + /// Created user object /// void CreateUser(NancyContext context, User body); @@ -102,7 +114,7 @@ public interface UserService /// /// /// Context of request - /// List of user object (optional) + /// List of user object /// void CreateUsersWithArrayInput(NancyContext context, List body); @@ -110,7 +122,7 @@ public interface UserService /// ///
    /// Context of request - /// List of user object (optional) + /// List of user object /// void CreateUsersWithListInput(NancyContext context, List body); @@ -134,8 +146,8 @@ public interface UserService /// ///
    /// Context of request - /// The user name for login (optional) - /// The password for login in clear text (optional) + /// The user name for login + /// The password for login in clear text /// string string LoginUser(NancyContext context, string username, string password); @@ -151,7 +163,7 @@ public interface UserService ///
    /// Context of request /// name that need to be deleted - /// Updated user object (optional) + /// Updated user object /// void UpdateUser(NancyContext context, string username, User body); } diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config index 6d8651cdcf4..2575d1b4d77 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/samples/server/petstore/rails5/.swagger-codegen-ignore b/samples/server/petstore/rails5/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/rails5/.swagger-codegen-ignore +++ b/samples/server/petstore/rails5/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/rails5/app/controllers/pet_controllers.rb b/samples/server/petstore/rails5/app/controllers/pets_controller.rb similarity index 100% rename from samples/server/petstore/rails5/app/controllers/pet_controllers.rb rename to samples/server/petstore/rails5/app/controllers/pets_controller.rb diff --git a/samples/server/petstore/rails5/app/controllers/store_controllers.rb b/samples/server/petstore/rails5/app/controllers/stores_controller.rb similarity index 100% rename from samples/server/petstore/rails5/app/controllers/store_controllers.rb rename to samples/server/petstore/rails5/app/controllers/stores_controller.rb diff --git a/samples/server/petstore/rails5/app/controllers/user_controllers.rb b/samples/server/petstore/rails5/app/controllers/users_controller.rb similarity index 100% rename from samples/server/petstore/rails5/app/controllers/user_controllers.rb rename to samples/server/petstore/rails5/app/controllers/users_controller.rb diff --git a/samples/server/petstore/rails5/app/models/pet.rb b/samples/server/petstore/rails5/app/models/pet.rb index da927b6260e..e077b528bc7 100644 --- a/samples/server/petstore/rails5/app/models/pet.rb +++ b/samples/server/petstore/rails5/app/models/pet.rb @@ -23,8 +23,8 @@ class Pet < ApplicationRecord - validate_presence_of :name - validate_presence_of :photo_urls + validates_presence_of :name + validates_presence_of :photo_urls serialize :photo_urls, Array serialize :tags, Array diff --git a/samples/server/petstore/rails5/db/migrate/0_init_tables.rb b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb index 5fa060fb4dc..7bc2663f162 100644 --- a/samples/server/petstore/rails5/db/migrate/0_init_tables.rb +++ b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb @@ -23,7 +23,7 @@ class InitTables < ActiveRecord::Migration def change - create_table :api_response, id: false do |t| + create_table "api_response".pluralize.to_sym, id: false do |t| t.integer :code t.string :type t.string :message @@ -31,14 +31,14 @@ def change t.timestamps end - create_table :category, id: false do |t| + create_table "category".pluralize.to_sym, id: false do |t| t.integer :id t.string :name t.timestamps end - create_table :order, id: false do |t| + create_table "order".pluralize.to_sym, id: false do |t| t.integer :id t.integer :pet_id t.integer :quantity @@ -49,7 +49,7 @@ def change t.timestamps end - create_table :pet, id: false do |t| + create_table "pet".pluralize.to_sym, id: false do |t| t.integer :id t.string :category t.string :name @@ -60,14 +60,14 @@ def change t.timestamps end - create_table :tag, id: false do |t| + create_table "tag".pluralize.to_sym, id: false do |t| t.integer :id t.string :name t.timestamps end - create_table :user, id: false do |t| + create_table "user".pluralize.to_sym, id: false do |t| t.integer :id t.string :username t.string :first_name diff --git a/samples/server/petstore/scalatra/.swagger-codegen-ignore b/samples/server/petstore/scalatra/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/scalatra/.swagger-codegen-ignore +++ b/samples/server/petstore/scalatra/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/scalatra/pom.xml b/samples/server/petstore/scalatra/pom.xml new file mode 100644 index 00000000000..bc1a6f92cdf --- /dev/null +++ b/samples/server/petstore/scalatra/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + com.wordnik + scalatra-server + pom + 1.0-SNAPSHOT + Scalatra server + + + + org.codehaus.mojo + exec-maven-plugin + 1.5.0 + + + sbt-test + integration-test + + exec + + + /usr/local/bin/sbt + + test + + + + + + + + diff --git a/samples/server/petstore/scalatra/sbt b/samples/server/petstore/scalatra/sbt old mode 100755 new mode 100644 diff --git a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala index c78a1132148..385bf47207c 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala @@ -34,9 +34,9 @@ class ScalatraBootstrap extends LifeCycle { override def init(context: ServletContext) { implicit val system = ActorSystem("appActorSystem") try { - context mount (new PetApi, "/Pet/*") - context mount (new StoreApi, "/Store/*") - context mount (new UserApi, "/User/*") + context mount (new PetApi, "/v2/Pet/*") + context mount (new StoreApi, "/v2/Store/*") + context mount (new UserApi, "/v2/User/*") context mount (new ResourcesApp, "/api-docs/*") } catch { diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 56288e3518f..9995f630123 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -25,8 +25,8 @@ package com.wordnik.client.api import com.wordnik.client.model.Pet -import java.io.File import com.wordnik.client.model.ApiResponse +import java.io.File import java.io.File @@ -39,14 +39,14 @@ import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintE import scala.collection.JavaConverters._ -class PetApi (implicit val swagger: Swagger) extends ScalatraServlet +class PetApi (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "PetApi" - override protected val applicationName: Option[String] = Some("Pet") + override protected val applicationName: Option[String] = Some("/v2/Pet") before() { contentType = formats("json") @@ -62,7 +62,8 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet post("/pet",operation(addPetOperation)) { - bodyParam[Pet]("body").description("") + val body = parsedBody.extract[Pet] + println("body: " + body) } @@ -70,11 +71,10 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet val deletePetOperation = (apiOperation[Unit]("deletePet") summary "Deletes a pet" - parameters(pathParam[Long]("petId").description(""), - ) + parameters(pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional) ) - delete("/pet/{petId}",operation(deletePetOperation)) { + delete("/pet/:petId",operation(deletePetOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -142,7 +142,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description("")) ) - get("/pet/{petId}",operation(getPetByIdOperation)) { + get("/pet/:petId",operation(getPetByIdOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -160,7 +160,8 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet put("/pet",operation(updatePetOperation)) { - bodyParam[Pet]("body").description("") + val body = parsedBody.extract[Pet] + println("body: " + body) } @@ -168,12 +169,10 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm") summary "Updates a pet in the store with form data" - parameters(pathParam[Long]("petId").description(""), - formParam[String]("name").description("").optional, - formParam[String]("status").description("").optional) + parameters(pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional) ) - post("/pet/{petId}",operation(updatePetWithFormOperation)) { + post("/pet/:petId",operation(updatePetWithFormOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -195,12 +194,10 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet val uploadFileOperation = (apiOperation[ApiResponse]("uploadFile") summary "uploads an image" - parameters(pathParam[Long]("petId").description(""), - formParam[String]("additionalMetadata").description("").optional, - formParam[File]("file").description("").optional) + parameters(pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional) ) - post("/pet/{petId}/uploadImage",operation(uploadFileOperation)) { + post("/pet/:petId/uploadImage",operation(uploadFileOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -215,4 +212,4 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet println("file: " + file) } -} \ No newline at end of file +} diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index b2a8df92b39..3a6d8e8e9bc 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -37,14 +37,14 @@ import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintE import scala.collection.JavaConverters._ -class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet +class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "StoreApi" - override protected val applicationName: Option[String] = Some("Store") + override protected val applicationName: Option[String] = Some("/v2/Store") before() { contentType = formats("json") @@ -57,7 +57,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[String]("orderId").description("")) ) - delete("/store/order/{orderId}",operation(deleteOrderOperation)) { + delete("/store/order/:orderId",operation(deleteOrderOperation)) { val orderId = params.getOrElse("orderId", halt(400)) @@ -82,7 +82,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("orderId").description("")) ) - get("/store/order/{orderId}",operation(getOrderByIdOperation)) { + get("/store/order/:orderId",operation(getOrderByIdOperation)) { val orderId = params.getOrElse("orderId", halt(400)) @@ -100,8 +100,9 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet post("/store/order",operation(placeOrderOperation)) { - bodyParam[Order]("body").description("") + val body = parsedBody.extract[Order] + println("body: " + body) } -} \ No newline at end of file +} diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala index 7103ade331e..4b00593af62 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -37,14 +37,14 @@ import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintE import scala.collection.JavaConverters._ -class UserApi (implicit val swagger: Swagger) extends ScalatraServlet +class UserApi (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "UserApi" - override protected val applicationName: Option[String] = Some("User") + override protected val applicationName: Option[String] = Some("/v2/User") before() { contentType = formats("json") @@ -60,7 +60,8 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet post("/user",operation(createUserOperation)) { - bodyParam[User]("body").description("") + val body = parsedBody.extract[User] + println("body: " + body) } @@ -74,7 +75,8 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) { - bodyParam[List[User]]("body").description("") + val body = parsedBody.extract[List[User]] + println("body: " + body) } @@ -88,7 +90,8 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet post("/user/createWithList",operation(createUsersWithListInputOperation)) { - bodyParam[List[User]]("body").description("") + val body = parsedBody.extract[List[User]] + println("body: " + body) } @@ -99,7 +102,7 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[String]("username").description("")) ) - delete("/user/{username}",operation(deleteUserOperation)) { + delete("/user/:username",operation(deleteUserOperation)) { val username = params.getOrElse("username", halt(400)) @@ -114,7 +117,7 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[String]("username").description("")) ) - get("/user/{username}",operation(getUserByNameOperation)) { + get("/user/:username",operation(getUserByNameOperation)) { val username = params.getOrElse("username", halt(400)) @@ -126,8 +129,7 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet val loginUserOperation = (apiOperation[String]("loginUser") summary "Logs user into the system" - parameters(queryParam[String]("username").description(""), - queryParam[String]("password").description("")) + parameters(queryParam[String]("username").description(""), queryParam[String]("password").description("")) ) get("/user/login",operation(loginUserOperation)) { @@ -157,11 +159,10 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet val updateUserOperation = (apiOperation[Unit]("updateUser") summary "Updated user" - parameters(pathParam[String]("username").description(""), - bodyParam[User]("body").description("")) + parameters(pathParam[String]("username").description(""), bodyParam[User]("body").description("")) ) - put("/user/{username}",operation(updateUserOperation)) { + put("/user/:username",operation(updateUserOperation)) { val username = params.getOrElse("username", halt(400)) @@ -169,8 +170,9 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet println("username: " + username) - bodyParam[User]("body").description("") + val body = parsedBody.extract[User] + println("body: " + body) } -} \ No newline at end of file +} diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala index 90396f5de75..13658983f75 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala @@ -25,9 +25,8 @@ package com.wordnik.client.model - case class ApiResponse ( code: Option[Int], -type: Option[String], -message: Option[String] + _type: Option[String], + message: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala index 4bdadfbbe5c..ab54f62c0ea 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala @@ -25,8 +25,7 @@ package com.wordnik.client.model - case class Category ( id: Option[Long], -name: Option[String] + name: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala index 6f399b0d1c3..b55c2ab26ef 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala @@ -26,12 +26,12 @@ package com.wordnik.client.model import java.util.Date - case class Order ( id: Option[Long], -petId: Option[Long], -quantity: Option[Int], -shipDate: Option[Date], -status: Option[String], // Order Status -complete: Option[Boolean] + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[Date], + /* Order Status */ + status: Option[String], + complete: Option[Boolean] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala index 01aa08e73ce..7d3c9093595 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala @@ -24,15 +24,13 @@ package com.wordnik.client.model -import com.wordnik.client.model.Category -import com.wordnik.client.model.Tag - case class Pet ( id: Option[Long], -category: Option[Category], -name: String, -photoUrls: List[String], -tags: Option[List[Tag]], -status: Option[String] // pet status in the store + category: Option[Category], + name: String, + photoUrls: List[String], + tags: Option[List[Tag]], + /* pet status in the store */ + status: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala index a3d34e8d557..888c2f31346 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala @@ -25,8 +25,7 @@ package com.wordnik.client.model - case class Tag ( id: Option[Long], -name: Option[String] + name: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala index ff792d91371..3b4f9dc68e0 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala @@ -25,14 +25,14 @@ package com.wordnik.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], -userStatus: Option[Int] // User Status + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + /* User Status */ + userStatus: Option[Int] ) diff --git a/samples/server/petstore/silex/.swagger-codegen-ignore b/samples/server/petstore/silex/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/silex/.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/silex/LICENSE b/samples/server/petstore/silex/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/silex/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/silex/SwaggerServer/index.php b/samples/server/petstore/silex/SwaggerServer/index.php index aba755a883a..10b446e9974 100644 --- a/samples/server/petstore/silex/SwaggerServer/index.php +++ b/samples/server/petstore/silex/SwaggerServer/index.php @@ -8,140 +8,140 @@ $app = new Silex\Application(); -$app->POST('/pet', function(Application $app, Request $request) { +$app->POST('/v2/pet', function(Application $app, Request $request) { return new Response('How about implementing addPet as a POST method ?'); }); -$app->DELETE('/pet/{petId}', function(Application $app, Request $request, $pet_id) { +$app->DELETE('/v2/pet/{petId}', function(Application $app, Request $request, $pet_id) { return new Response('How about implementing deletePet as a DELETE method ?'); }); -$app->GET('/pet/findByStatus', function(Application $app, Request $request) { +$app->GET('/v2/pet/findByStatus', function(Application $app, Request $request) { $status = $request->get('status'); return new Response('How about implementing findPetsByStatus as a GET method ?'); }); -$app->GET('/pet/findByTags', function(Application $app, Request $request) { +$app->GET('/v2/pet/findByTags', function(Application $app, Request $request) { $tags = $request->get('tags'); return new Response('How about implementing findPetsByTags as a GET method ?'); }); -$app->GET('/pet/{petId}', function(Application $app, Request $request, $pet_id) { +$app->GET('/v2/pet/{petId}', function(Application $app, Request $request, $pet_id) { return new Response('How about implementing getPetById as a GET method ?'); }); -$app->PUT('/pet', function(Application $app, Request $request) { +$app->PUT('/v2/pet', function(Application $app, Request $request) { return new Response('How about implementing updatePet as a PUT method ?'); }); -$app->POST('/pet/{petId}', function(Application $app, Request $request, $pet_id) { +$app->POST('/v2/pet/{petId}', function(Application $app, Request $request, $pet_id) { $name = $request->get('name'); $status = $request->get('status'); return new Response('How about implementing updatePetWithForm as a POST method ?'); }); -$app->POST('/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) { +$app->POST('/v2/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) { $additional_metadata = $request->get('additional_metadata'); $file = $request->get('file'); return new Response('How about implementing uploadFile as a POST method ?'); }); -$app->DELETE('/store/order/{orderId}', function(Application $app, Request $request, $order_id) { +$app->DELETE('/v2/store/order/{orderId}', function(Application $app, Request $request, $order_id) { return new Response('How about implementing deleteOrder as a DELETE method ?'); }); -$app->GET('/store/inventory', function(Application $app, Request $request) { +$app->GET('/v2/store/inventory', function(Application $app, Request $request) { return new Response('How about implementing getInventory as a GET method ?'); }); -$app->GET('/store/order/{orderId}', function(Application $app, Request $request, $order_id) { +$app->GET('/v2/store/order/{orderId}', function(Application $app, Request $request, $order_id) { return new Response('How about implementing getOrderById as a GET method ?'); }); -$app->POST('/store/order', function(Application $app, Request $request) { +$app->POST('/v2/store/order', function(Application $app, Request $request) { return new Response('How about implementing placeOrder as a POST method ?'); }); -$app->POST('/user', function(Application $app, Request $request) { +$app->POST('/v2/user', function(Application $app, Request $request) { return new Response('How about implementing createUser as a POST method ?'); }); -$app->POST('/user/createWithArray', function(Application $app, Request $request) { +$app->POST('/v2/user/createWithArray', function(Application $app, Request $request) { return new Response('How about implementing createUsersWithArrayInput as a POST method ?'); }); -$app->POST('/user/createWithList', function(Application $app, Request $request) { +$app->POST('/v2/user/createWithList', function(Application $app, Request $request) { return new Response('How about implementing createUsersWithListInput as a POST method ?'); }); -$app->DELETE('/user/{username}', function(Application $app, Request $request, $username) { +$app->DELETE('/v2/user/{username}', function(Application $app, Request $request, $username) { return new Response('How about implementing deleteUser as a DELETE method ?'); }); -$app->GET('/user/{username}', function(Application $app, Request $request, $username) { +$app->GET('/v2/user/{username}', function(Application $app, Request $request, $username) { return new Response('How about implementing getUserByName as a GET method ?'); }); -$app->GET('/user/login', function(Application $app, Request $request) { +$app->GET('/v2/user/login', function(Application $app, Request $request) { $username = $request->get('username'); $password = $request->get('password'); return new Response('How about implementing loginUser as a GET method ?'); }); -$app->GET('/user/logout', function(Application $app, Request $request) { +$app->GET('/v2/user/logout', function(Application $app, Request $request) { return new Response('How about implementing logoutUser as a GET method ?'); }); -$app->PUT('/user/{username}', function(Application $app, Request $request, $username) { +$app->PUT('/v2/user/{username}', function(Application $app, Request $request, $username) { return new Response('How about implementing updateUser as a PUT method ?'); diff --git a/samples/server/petstore/sinatra/.swagger-codegen-ignore b/samples/server/petstore/sinatra/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/sinatra/.swagger-codegen-ignore +++ b/samples/server/petstore/sinatra/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/slim/.swagger-codegen-ignore b/samples/server/petstore/slim/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/slim/.swagger-codegen-ignore +++ b/samples/server/petstore/slim/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/slim/index.php b/samples/server/petstore/slim/index.php index 0138feb1d55..74d6648df9f 100644 --- a/samples/server/petstore/slim/index.php +++ b/samples/server/petstore/slim/index.php @@ -15,7 +15,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet', function($request, $response, $args) { +$app->POST('/v2/pet', function($request, $response, $args) { @@ -31,7 +31,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/pet/{petId}', function($request, $response, $args) { +$app->DELETE('/v2/pet/{petId}', function($request, $response, $args) { $headers = $request->getHeaders(); @@ -47,7 +47,7 @@ * Notes: Multiple status values can be provided with comma separated strings * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByStatus', function($request, $response, $args) { +$app->GET('/v2/pet/findByStatus', function($request, $response, $args) { $queryParams = $request->getQueryParams(); $status = $queryParams['status']; @@ -64,7 +64,7 @@ * Notes: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByTags', function($request, $response, $args) { +$app->GET('/v2/pet/findByTags', function($request, $response, $args) { $queryParams = $request->getQueryParams(); $tags = $queryParams['tags']; @@ -81,7 +81,7 @@ * Notes: Returns a single pet * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/{petId}', function($request, $response, $args) { +$app->GET('/v2/pet/{petId}', function($request, $response, $args) { @@ -97,7 +97,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->PUT('/pet', function($request, $response, $args) { +$app->PUT('/v2/pet', function($request, $response, $args) { @@ -113,7 +113,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet/{petId}', function($request, $response, $args) { +$app->POST('/v2/pet/{petId}', function($request, $response, $args) { $name = $args['name']; $status = $args['status']; @@ -129,7 +129,7 @@ * Notes: * Output-Formats: [application/json] */ -$app->POST('/pet/{petId}/uploadImage', function($request, $response, $args) { +$app->POST('/v2/pet/{petId}/uploadImage', function($request, $response, $args) { $additionalMetadata = $args['additionalMetadata']; $file = $args['file']; @@ -145,7 +145,7 @@ * Notes: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/store/order/{orderId}', function($request, $response, $args) { +$app->DELETE('/v2/store/order/{orderId}', function($request, $response, $args) { @@ -161,7 +161,7 @@ * Notes: Returns a map of status codes to quantities * Output-Formats: [application/json] */ -$app->GET('/store/inventory', function($request, $response, $args) { +$app->GET('/v2/store/inventory', function($request, $response, $args) { @@ -177,7 +177,7 @@ * Notes: For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Output-Formats: [application/xml, application/json] */ -$app->GET('/store/order/{orderId}', function($request, $response, $args) { +$app->GET('/v2/store/order/{orderId}', function($request, $response, $args) { @@ -193,7 +193,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/store/order', function($request, $response, $args) { +$app->POST('/v2/store/order', function($request, $response, $args) { @@ -209,7 +209,7 @@ * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->POST('/user', function($request, $response, $args) { +$app->POST('/v2/user', function($request, $response, $args) { @@ -225,7 +225,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithArray', function($request, $response, $args) { +$app->POST('/v2/user/createWithArray', function($request, $response, $args) { @@ -241,7 +241,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithList', function($request, $response, $args) { +$app->POST('/v2/user/createWithList', function($request, $response, $args) { @@ -257,7 +257,7 @@ * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/user/{username}', function($request, $response, $args) { +$app->DELETE('/v2/user/{username}', function($request, $response, $args) { @@ -273,7 +273,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/{username}', function($request, $response, $args) { +$app->GET('/v2/user/{username}', function($request, $response, $args) { @@ -289,7 +289,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/login', function($request, $response, $args) { +$app->GET('/v2/user/login', function($request, $response, $args) { $queryParams = $request->getQueryParams(); $username = $queryParams['username']; $password = $queryParams['password']; @@ -306,7 +306,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/logout', function($request, $response, $args) { +$app->GET('/v2/user/logout', function($request, $response, $args) { @@ -322,7 +322,7 @@ * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->PUT('/user/{username}', function($request, $response, $args) { +$app->PUT('/v2/user/{username}', function($request, $response, $args) { diff --git a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md index 9f609674c80..b670aa133b4 100644 --- a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md +++ b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md @@ -12,7 +12,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the `ContainerInterface` in a depency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md index 04eb3aea023..63cc3fb0f40 100644 --- a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md +++ b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md @@ -15,7 +15,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the delegate lookup feature in a dependency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c b/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c index 239c01d683d..821365bf127 100644 --- a/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c +++ b/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c @@ -419,7 +419,7 @@ static zval *pimple_object_read_dimension(zval *object, zval *offset, int type T } if (zend_hash_index_exists(&pimple_obj->factories, retval->handle_num)) { - /* Service is a factory, call it everytime and never cache its result */ + /* Service is a factory, call it every time and never cache its result */ PIMPLE_CALL_CB Z_DELREF_P(retval_ptr_ptr); /* fetch dim addr will increment refcount */ return retval_ptr_ptr; diff --git a/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php b/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php index 96d82cb81fb..639d9b9b470 100644 --- a/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php +++ b/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php @@ -110,7 +110,7 @@ public function add($callable) } /** - * Calling a non-existant method on App checks to see if there's an item + * Calling a non-existent method on App checks to see if there's an item * in the container that is callable and if so, calls it. * * @param string $method diff --git a/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore b/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore +++ b/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/spring-mvc-j8-async/pom.xml b/samples/server/petstore/spring-mvc-j8-async/pom.xml index f8916b3ad47..d79b6aba9da 100644 --- a/samples/server/petstore/spring-mvc-j8-async/pom.xml +++ b/samples/server/petstore/spring-mvc-j8-async/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-spring-server + swagger-spring jar - swagger-spring-server + swagger-spring 1.0.0 src/main/java 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 new file mode 100644 index 00000000000..2f2140bc068 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,157 @@ +package io.swagger.api; + +import io.swagger.model.Client; +import java.time.OffsetDateTime; +import java.time.LocalDate; +import java.math.BigDecimal; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import java.util.concurrent.CompletableFuture; + + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + default CompletableFuture> testClientModel( + +@ApiParam(value = "client model" ,required=true ) @RequestBody Client body + +) { + // do some magic! + return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + } + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @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) + 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="patternWithoutDelimiter", 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 +) { + // do some magic! + return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + } + + + @ApiOperation(value = "To test enum parameters", notes = "", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.GET) + default CompletableFuture> testEnumParameters( + + +@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray +, + + +@ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString +, +@ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @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 = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray + + + +,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString + + + +,@ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger + + + +, + + +@ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble +) { + // do some magic! + return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + } + +} 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 new file mode 100644 index 00000000000..31729a28177 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,10 @@ +package io.swagger.api; + +import org.springframework.stereotype.Controller; + + + +@Controller +public class FakeApiController implements FakeApi { + +} 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 5cac886b443..8b23618a5a3 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 @@ -28,14 +28,18 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet", 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 ) @RequestBody Pet body) { + default CompletableFuture> addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } @@ -46,13 +50,21 @@ default CompletableFuture> addPet(@ApiParam(value = "Pet ob @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @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) { + 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 + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } @@ -63,14 +75,18 @@ default CompletableFuture> deletePet(@ApiParam(value = "Pet @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status) { + default CompletableFuture>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); } @@ -81,14 +97,18 @@ default CompletableFuture>> findPetsByStatus(@ApiParam( @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + default CompletableFuture>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); } @@ -96,7 +116,7 @@ default CompletableFuture>> findPetsByTags(@ApiParam(va @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -104,7 +124,11 @@ default CompletableFuture>> findPetsByTags(@ApiParam(va @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) { + default CompletableFuture> getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } @@ -115,7 +139,7 @@ default CompletableFuture> getPetById(@ApiParam(value = "ID @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -124,7 +148,11 @@ default CompletableFuture> getPetById(@ApiParam(value = "ID 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 ) @RequestBody Pet body) { + default CompletableFuture> updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } @@ -135,14 +163,26 @@ default CompletableFuture> updatePet(@ApiParam(value = "Pet @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", 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) { + 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 +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } @@ -153,14 +193,26 @@ default CompletableFuture> updatePetWithForm(@ApiParam(valu @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - 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") @RequestPart("file") MultipartFile file) { + 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") @RequestPart("file") MultipartFile file +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java index 05d94900cd5..7ff6fbef439 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 @@ -22,14 +22,18 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default CompletableFuture> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + default CompletableFuture> deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } @@ -37,7 +41,7 @@ default CompletableFuture> deleteOrder(@ApiParam(value = "I @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -49,7 +53,7 @@ default CompletableFuture>> getInventory() { } - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -57,20 +61,28 @@ default CompletableFuture>> getInventory() { @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + default CompletableFuture> getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + default CompletableFuture> placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } 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 4badb1ac87c..8341d719375 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 @@ -22,56 +22,72 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + default CompletableFuture> createUser( + +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + default CompletableFuture> createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + default CompletableFuture> createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default CompletableFuture> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + default CompletableFuture> deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -79,26 +95,38 @@ default CompletableFuture> deleteUser(@ApiParam(value = "Th @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) { + default CompletableFuture> getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + default CompletableFuture> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username + + + +,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -110,14 +138,22 @@ default CompletableFuture> logoutUser() { } - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/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 ) @RequestBody User body) { + default CompletableFuture> updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + + +, + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body + +) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java new file mode 100644 index 00000000000..4aaf6cd1c0c --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger.configuration; + +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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java index 0039472ceef..962607f9340 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -17,7 +17,7 @@ public class SwaggerDocumentationConfig { ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](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.") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index c7614b0015b..e05672181db 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -1,14 +1,21 @@ package io.swagger.configuration; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Import; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.List; + @Configuration @ComponentScan(basePackages = "io.swagger.api") @@ -51,4 +58,14 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { } } + @Override + public void configureMessageConverters(List> converters) { + ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .dateFormat( new RFC3339DateFormat()) + .build(); + converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); + super.configureMessageConverters(converters); + } + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + 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) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..de739ed501c --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + 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) { + 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) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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 getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index 67bc75b3b10..ba1ecfdb2b8 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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 = new ArrayList(); + + 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) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..446649217c8 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,214 @@ +package io.swagger.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; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + + 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; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + 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 new file mode 100644 index 00000000000..242a20cfc3b --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,363 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.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 String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @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.0 + * maximum: 200.0 + * @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(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..3f5492a2e62 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + 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) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..ea443a94338 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String 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) { + 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..82f447004ee 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,81 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +84,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +110,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..09085fb52dc --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,126 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index 28b6d40e799..cee3ae6d708 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -2,27 +2,37 @@ 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.time.OffsetDateTime; - - - - +/** + * Order + */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private OffsetDateTime shipDate = null; + @JsonProperty("shipDate") + private OffsetDateTime shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +44,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public OffsetDateTime getShipDate() { return shipDate; } + public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +182,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -186,7 +214,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index 24092cbee25..823d25e05a0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ 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; @@ -10,23 +11,34 @@ 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(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +50,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +195,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -189,7 +227,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..50a2a7e4184 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,88 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index f26d84e74b2..846812a5031 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index 5dc291a7889..52c5fff826e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -2,165 +2,186 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -204,7 +225,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/resources/swagger.properties b/samples/server/petstore/spring-mvc-j8-async/src/main/resources/swagger.properties index 858a5f007b5..8d3a7a8292b 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/resources/swagger.properties +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/resources/swagger.properties @@ -1,2 +1,2 @@ -springfox.documentation.swagger.v2.path=/api-docs -#server.port=8090 \ No newline at end of file +springfox.documentation.swagger.v2.path=/api-docs +#server.port=8090 diff --git a/samples/server/petstore/spring-mvc/.swagger-codegen-ignore b/samples/server/petstore/spring-mvc/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/spring-mvc/.swagger-codegen-ignore +++ b/samples/server/petstore/spring-mvc/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# 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: diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index df0c832d955..c3a46a657d7 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-spring-server + swagger-spring-mvc-server jar - swagger-spring-server + swagger-spring-mvc-server 1.0.0 src/main/java 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 new file mode 100644 index 00000000000..262a5fe9a16 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,146 @@ +package io.swagger.api; + +import io.swagger.model.Client; +import org.joda.time.LocalDate; +import java.math.BigDecimal; +import org.joda.time.DateTime; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + ResponseEntity testClientModel( + +@ApiParam(value = "client model" ,required=true ) @RequestBody Client body + +); + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @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="patternWithoutDelimiter", 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) DateTime dateTime +, + + +@ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password +); + + + @ApiOperation(value = "To test enum parameters", notes = "", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.GET) + ResponseEntity testEnumParameters( + + +@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray +, + + +@ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString +, +@ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @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 = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray + + + +,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString + + + +,@ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger + + + +, + + +@ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble +); + +} 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 new file mode 100644 index 00000000000..2115ca4cf68 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,149 @@ +package io.swagger.api; + +import io.swagger.model.Client; +import org.joda.time.LocalDate; +import java.math.BigDecimal; +import org.joda.time.DateTime; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class FakeApiController implements FakeApi { + + public ResponseEntity testClientModel( + +@ApiParam(value = "client model" ,required=true ) @RequestBody Client body + +) { + // 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="patternWithoutDelimiter", 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) DateTime dateTime +, + + + +@ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password +) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity testEnumParameters( + + +@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray +, + + + +@ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString +, + +@ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @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 = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray + + + +, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString + + + +, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger + + + +, + + + +@ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble +) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} 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 f0f76394bf3..ea0122441c1 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 @@ -26,14 +26,18 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @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 ) @RequestBody Pet body); + ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +); @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { @@ -41,14 +45,21 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @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); + ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + + +, +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + + +); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -56,14 +67,18 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + + +); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -71,19 +86,23 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + + +); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -91,7 +110,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @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); + ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + + +); @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { @@ -99,7 +122,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -108,7 +131,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru 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 ) @RequestBody Pet body); + ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +); @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { @@ -116,16 +143,26 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @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); + ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + + +, + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -133,15 +170,25 @@ ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs t @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + + +, + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +); } diff --git a/samples/server/petstore/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 3a2dcab47b6..8b95d74de51 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 @@ -23,47 +23,99 @@ @Controller public class PetApiController implements PetApi { - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + public ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + public ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + + +, + +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status) { + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + + +) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + + +) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + public ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + public ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, - @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + public ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + + +, + + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, + + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + public ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + + +, + + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, + + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/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 f67745dfa32..74aceedfafe 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 @@ -20,19 +20,23 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + + +); @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -41,7 +45,7 @@ public interface StoreApi { ResponseEntity> getInventory(); - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -49,16 +53,24 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + +); - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @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 bd582ae1a94..6132f766a07 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 @@ -22,7 +22,11 @@ @Controller public class StoreApiController implements StoreApi { - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + public ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } @@ -32,12 +36,20 @@ public ResponseEntity> getInventory() { return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + public ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + public ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/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 508a5c1863d..e9b154cd012 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 @@ -20,44 +20,60 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + ResponseEntity createUser( +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) +); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + + +); - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -65,21 +81,32 @@ 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); + ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + + +); - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + +,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + + +); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -88,14 +115,21 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re ResponseEntity logoutUser(); - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/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 ) @RequestBody User body); + ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + + +, + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body + +); } diff --git a/samples/server/petstore/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 a5a6d4d4505..322d7053c18 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 @@ -22,33 +22,61 @@ @Controller public class UserApiController implements UserApi { - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + public ResponseEntity createUser( + +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + public ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + public ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + public ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + public ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username + + + +, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } @@ -58,8 +86,16 @@ public ResponseEntity logoutUser() { return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + public ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + + +, + + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java new file mode 100644 index 00000000000..4aaf6cd1c0c --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger.configuration; + +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/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java index bd923ba0350..5658793e134 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -17,7 +17,7 @@ public class SwaggerDocumentationConfig { ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](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.") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index c7614b0015b..e05672181db 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -1,14 +1,21 @@ package io.swagger.configuration; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Import; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.List; + @Configuration @ComponentScan(basePackages = "io.swagger.api") @@ -51,4 +58,14 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { } } + @Override + public void configureMessageConverters(List> converters) { + ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .dateFormat( new RFC3339DateFormat()) + .build(); + converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); + super.configureMessageConverters(converters); + } + } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + 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) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..de739ed501c --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +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/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + 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) { + 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) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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 getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index 67bc75b3b10..ba1ecfdb2b8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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 = new ArrayList(); + + 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) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..446649217c8 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,214 @@ +package io.swagger.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; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + + 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; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + 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 new file mode 100644 index 00000000000..8d3cd2bec93 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,363 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +/** + * 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 DateTime dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @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.0 + * maximum: 200.0 + * @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(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..3f5492a2e62 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + 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) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..36106536c7b --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..82f447004ee 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,81 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +84,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +110,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..09085fb52dc --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,126 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index 55859fc4089..2863c127f60 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -2,27 +2,37 @@ 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.joda.time.DateTime; - - - - +/** + * Order + */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private DateTime shipDate = null; + @JsonProperty("shipDate") + private DateTime shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +44,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +182,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -186,7 +214,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index 24092cbee25..823d25e05a0 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ 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; @@ -10,23 +11,34 @@ 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(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +50,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +195,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -189,7 +227,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..50a2a7e4184 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,88 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index f26d84e74b2..846812a5031 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 5dc291a7889..52c5fff826e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -2,165 +2,186 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -204,7 +225,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/spring-mvc/src/main/resources/swagger.properties b/samples/server/petstore/spring-mvc/src/main/resources/swagger.properties index 858a5f007b5..8d3a7a8292b 100644 --- a/samples/server/petstore/spring-mvc/src/main/resources/swagger.properties +++ b/samples/server/petstore/spring-mvc/src/main/resources/swagger.properties @@ -1,2 +1,2 @@ -springfox.documentation.swagger.v2.path=/api-docs -#server.port=8090 \ No newline at end of file +springfox.documentation.swagger.v2.path=/api-docs +#server.port=8090 diff --git a/samples/server/petstore/springboot/pom.xml b/samples/server/petstore/springboot/pom.xml index 4cf50070b8d..fdb0b535b34 100644 --- a/samples/server/petstore/springboot/pom.xml +++ b/samples/server/petstore/springboot/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-spring-server + swagger-spring jar - swagger-spring-server + swagger-spring 1.0.0 1.7 diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java b/samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java new file mode 100644 index 00000000000..0c3d276d2d4 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger; + +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/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java index 2cc65db2b81..c06fbae3c7a 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -1,36 +1,36 @@ -package io.swagger; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.ExitCodeGenerator; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@SpringBootApplication -@EnableSwagger2 -@ComponentScan(basePackages = "io.swagger") -public class Swagger2SpringBoot implements CommandLineRunner { - - @Override - public void run(String... arg0) throws Exception { - if (arg0.length > 0 && arg0[0].equals("exitcode")) { - throw new ExitException(); - } - } - - public static void main(String[] args) throws Exception { - new SpringApplication(Swagger2SpringBoot.class).run(args); - } - - class ExitException extends RuntimeException implements ExitCodeGenerator { - private static final long serialVersionUID = 1L; - - @Override - public int getExitCode() { - return 10; - } - - } -} \ No newline at end of file +package io.swagger; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "io.swagger") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} 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 new file mode 100644 index 00000000000..262a5fe9a16 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,146 @@ +package io.swagger.api; + +import io.swagger.model.Client; +import org.joda.time.LocalDate; +import java.math.BigDecimal; +import org.joda.time.DateTime; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + ResponseEntity testClientModel( + +@ApiParam(value = "client model" ,required=true ) @RequestBody Client body + +); + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @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="patternWithoutDelimiter", 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) DateTime dateTime +, + + +@ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password +); + + + @ApiOperation(value = "To test enum parameters", notes = "", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.GET) + ResponseEntity testEnumParameters( + + +@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray +, + + +@ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString +, +@ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @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 = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray + + + +,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString + + + +,@ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger + + + +, + + +@ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble +); + +} 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 new file mode 100644 index 00000000000..2115ca4cf68 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,149 @@ +package io.swagger.api; + +import io.swagger.model.Client; +import org.joda.time.LocalDate; +import java.math.BigDecimal; +import org.joda.time.DateTime; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class FakeApiController implements FakeApi { + + public ResponseEntity testClientModel( + +@ApiParam(value = "client model" ,required=true ) @RequestBody Client body + +) { + // 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="patternWithoutDelimiter", 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) DateTime dateTime +, + + + +@ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password +) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity testEnumParameters( + + +@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray +, + + + +@ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString +, + +@ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @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 = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray + + + +, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString + + + +, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger + + + +, + + + +@ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble +) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} 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 f0f76394bf3..ea0122441c1 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 @@ -26,14 +26,18 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @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 ) @RequestBody Pet body); + ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +); @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { @@ -41,14 +45,21 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @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); + ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + + +, +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + + +); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -56,14 +67,18 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + + +); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -71,19 +86,23 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + + +); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -91,7 +110,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @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); + ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + + +); @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { @@ -99,7 +122,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -108,7 +131,11 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru 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 ) @RequestBody Pet body); + ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +); @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { @@ -116,16 +143,26 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @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); + ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + + +, + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -133,15 +170,25 @@ ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs t @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + + +, + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index 3a2dcab47b6..8b95d74de51 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 @@ -23,47 +23,99 @@ @Controller public class PetApiController implements PetApi { - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + public ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + public ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + + +, + +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status) { + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status + + + +) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + + +) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + public ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + public ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, - @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + public ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + + +, + + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, + + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + public ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + + +, + + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, + + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java index f67745dfa32..74aceedfafe 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 @@ -20,19 +20,23 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + + +); @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -41,7 +45,7 @@ public interface StoreApi { ResponseEntity> getInventory(); - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -49,16 +53,24 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + +); - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body + +); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java index bd582ae1a94..6132f766a07 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 @@ -22,7 +22,11 @@ @Controller public class StoreApiController implements StoreApi { - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + public ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } @@ -32,12 +36,20 @@ public ResponseEntity> getInventory() { return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + public ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + public ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index 508a5c1863d..e9b154cd012 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 @@ -20,44 +20,60 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + ResponseEntity createUser( +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) +); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +); - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + + +); - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -65,21 +81,32 @@ 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); + ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + + +); - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + +,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + + +); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -88,14 +115,21 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re ResponseEntity logoutUser(); - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/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 ) @RequestBody User body); + ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + + +, + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body + +); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java index a5a6d4d4505..322d7053c18 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 @@ -22,33 +22,61 @@ @Controller public class UserApiController implements UserApi { - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + public ResponseEntity createUser( + +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + public ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + public ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + public ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + public ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username + + + +, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } @@ -58,8 +86,16 @@ public ResponseEntity logoutUser() { return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + public ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + + +, + + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body + +) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java index 14fcf37acff..d195523c1d3 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java @@ -1,16 +1,16 @@ -package io.swagger.configuration; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Home redirection to swagger api documentation - */ -@Controller -public class HomeController { - @RequestMapping(value = "/") - public String index() { - System.out.println("swagger-ui.html"); - return "redirect:swagger-ui.html"; - } -} \ No newline at end of file +package io.swagger.configuration; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java index bd923ba0350..5658793e134 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -17,7 +17,7 @@ public class SwaggerDocumentationConfig { ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](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.") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + 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) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..de739ed501c --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +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/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.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 true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + 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) { + 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) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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 getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java index 67bc75b3b10..ba1ecfdb2b8 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.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/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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 = new ArrayList(); + + 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) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + 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/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..446649217c8 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,214 @@ +package io.swagger.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; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + } + + @Override + @JsonValue + 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; + + 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; + } + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + 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 new file mode 100644 index 00000000000..8d3cd2bec93 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,363 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +/** + * 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 DateTime dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @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.0 + * maximum: 200.0 + * @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(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String 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/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..3f5492a2e62 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.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 = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + 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 = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + 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) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..36106536c7b --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + 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/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..82f447004ee 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,81 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +84,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +110,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..09085fb52dc --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,126 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.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/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java index 55859fc4089..2863c127f60 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -2,27 +2,37 @@ 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.joda.time.DateTime; - - - - +/** + * Order + */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private DateTime shipDate = null; + @JsonProperty("shipDate") + private DateTime shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +44,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +182,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + 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 @@ -186,7 +214,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java index 24092cbee25..823d25e05a0 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ 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; @@ -10,23 +11,34 @@ 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(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +50,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +195,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + 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 @@ -189,7 +227,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..50a2a7e4184 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,88 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * 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/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java index f26d84e74b2..846812a5031 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -2,56 +2,60 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +63,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +87,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java index 5dc291a7889..52c5fff826e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -2,165 +2,186 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - - +/** + * 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 = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + 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 @@ -204,7 +225,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/springboot/src/main/resources/application.properties b/samples/server/petstore/springboot/src/main/resources/application.properties index 858a5f007b5..a2ef8627027 100644 --- a/samples/server/petstore/springboot/src/main/resources/application.properties +++ b/samples/server/petstore/springboot/src/main/resources/application.properties @@ -1,2 +1,5 @@ -springfox.documentation.swagger.v2.path=/api-docs -#server.port=8090 \ No newline at end of file +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath=/v2 +server.port=8080 +spring.jackson.date-format=io.swagger.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore/undertow/.swagger-codegen-ignore b/samples/server/petstore/undertow/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/undertow/.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/undertow/LICENSE b/samples/server/petstore/undertow/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/undertow/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/undertow/README.md b/samples/server/petstore/undertow/README.md new file mode 100644 index 00000000000..9f1e36dd163 --- /dev/null +++ b/samples/server/petstore/undertow/README.md @@ -0,0 +1,28 @@ +# Swagger Undertow Server + +## Start server + +Run with + +``` +mvn package exec:exec +`` + +## Test + +By default, all endpoints are protected by OAuth jwt token verifier. It can be turned off with config change through for development. + + +In order to access the server, there is a long lived token below issued by my +oauth2 server [undertow-server-oauth2](https://github.com/networknt/undertow-server-oauth2) + +``` +Bearer eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTc4ODEzMjczNSwianRpIjoiNWtyM2ZWOHJaelBZNEJrSnNYZzFpQSIsImlhdCI6MTQ3Mjc3MjczNSwibmJmIjoxNDcyNzcyNjE1LCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJkZGNhZjBiYS0xMTMxLTIyMzItMzMxMy1kNmYyNzUzZjI1ZGMiLCJzY29wZSI6WyJhcGkuciIsImFwaS53Il19.gteJiy1uao8HLeWRljpZxHWUgQfofwmnFP-zv3EPUyXjyCOy3xclnfeTnTE39j8PgBwdFASPcDLLk1YfZJbsU6pLlmYXLtdpHDBsVmIRuch6LFPCVQ3JdqSQVci59OhSK0bBThGWqCD3UzDI_OnX4IVCAahcT9Bu94m5u_H_JNmwDf1XaP3Lt4I34buYMuRD9stchsnZi-tuIRkL13FARm1XA9aPZUMUXFdedBWDXo1zMREQ_qCJXOpaZDJM9Im0rIkq9wTEVU00pbRp_Vcdya3dfkFteBMHiwFVt6VNQaco5BXURDAIzXidwQxNEbX1ek03wra8AIani65ZK7fy_w +``` + +Postman is the best tool to test REST APIs + +Add "Authorization" header with value as above token and a dummy message will return from the generated stub. + + + diff --git a/samples/server/petstore/undertow/dependency-reduced-pom.xml b/samples/server/petstore/undertow/dependency-reduced-pom.xml new file mode 100644 index 00000000000..1a2b3705ce9 --- /dev/null +++ b/samples/server/petstore/undertow/dependency-reduced-pom.xml @@ -0,0 +1,114 @@ + + + + oss-parent + org.sonatype.oss + 5 + ../pom.xml/pom.xml + + 4.0.0 + io.swagger + swagger-undertow-server + swagger-undertow-server + 1.0.0 + + 2.2.0 + + + install + target + ${project.artifactId}-${project.version} + + + maven-shade-plugin + 2.4.3 + + + package + + shade + + + + + + + + + + + maven-jar-plugin + 2.6 + + + + com.networknt.server.Server + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + java + + -jar + target/${project.build.finalName}.jar + + + + + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + + + junit + junit + 4.12 + test + + + hamcrest-core + org.hamcrest + + + + + org.apache.httpcomponents + httpclient + 4.5.2 + test + + + + 4.1.2 + 1.10 + 3.1.2 + 2.2.0 + UTF-8 + 1.2 + 4.5.2 + 1.4.0.Final + 0.5.2 + 2.6 + 1.8 + 2.8.2 + 0.1.1 + 1.5.10 + 2.1.0-beta.124 + 1.7.21 + 2.5 + 1.1.7 + 4.12 + 4.5.3 + + + diff --git a/samples/server/petstore/undertow/pom.xml b/samples/server/petstore/undertow/pom.xml new file mode 100644 index 00000000000..f5e8cc42f31 --- /dev/null +++ b/samples/server/petstore/undertow/pom.xml @@ -0,0 +1,189 @@ + + + org.sonatype.oss + oss-parent + 5 + + 4.0.0 + io.swagger + swagger-undertow-server + jar + swagger-undertow-server + 1.0.0 + + 2.2.0 + + + + 1.8 + UTF-8 + 0.1.1 + 2.8.2 + 1.7.21 + 0.5.2 + 4.5.3 + 2.6 + 2.5 + 1.10 + 1.2 + 3.1.2 + 1.1.7 + 4.12 + 2.1.0-beta.124 + 1.4.0.Final + 2.2.0 + 4.5.2 + 4.1.2 + 1.5.10 + + + + + com.networknt + config + ${version.framework} + + + com.networknt + utility + ${version.framework} + + + com.networknt + security + ${version.framework} + + + com.networknt + client + ${version.framework} + + + com.networknt + audit + ${version.framework} + + + com.networknt + info + ${version.framework} + + + com.networknt + validator + ${version.framework} + + + com.networknt + server + ${version.framework} + + + + com.fasterxml.jackson.core + jackson-databind + ${version.jackson} + + + com.fasterxml.jackson.core + jackson-core + ${version.jackson} + + + com.jayway.jsonpath + json-path + ${version.jsonpath} + + + ch.qos.logback + logback-classic + ${version.logback} + + + io.undertow + undertow-core + ${version.undertow} + + + io.swagger + swagger-annotations + ${version.swagger} + + + + + junit + junit + ${version.junit} + test + + + org.apache.httpcomponents + httpclient + ${version.httpclient} + test + + + + + + + install + target + ${project.artifactId}-${project.version} + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.3 + + + package + + shade + + + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + com.networknt.server.Server + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + java + + -jar + target/${project.build.finalName}.jar + + + + + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + \ No newline at end of file diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/handler/PathHandlerProvider.java b/samples/server/petstore/undertow/src/main/java/io/swagger/handler/PathHandlerProvider.java new file mode 100644 index 00000000000..2dbba6aff95 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/handler/PathHandlerProvider.java @@ -0,0 +1,159 @@ +package io.swagger.handler; + +import com.networknt.config.Config; +import com.networknt.server.HandlerProvider; +import io.undertow.Handlers; +import io.undertow.server.HttpHandler; +import io.undertow.server.HttpServerExchange; +import io.undertow.util.Methods; + +public class PathHandlerProvider implements HandlerProvider { + + public HttpHandler getHandler() { + HttpHandler handler = Handlers.routing() + + + .add(Methods.POST, "/v2/pet", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("addPet"); + } + }) + + + .add(Methods.DELETE, "/v2/pet/{petId}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("deletePet"); + } + }) + + + .add(Methods.GET, "/v2/pet/findByStatus", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("findPetsByStatus"); + } + }) + + + .add(Methods.GET, "/v2/pet/findByTags", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("findPetsByTags"); + } + }) + + + .add(Methods.GET, "/v2/pet/{petId}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("getPetById"); + } + }) + + + .add(Methods.PUT, "/v2/pet", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("updatePet"); + } + }) + + + .add(Methods.POST, "/v2/pet/{petId}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("updatePetWithForm"); + } + }) + + + .add(Methods.POST, "/v2/pet/{petId}/uploadImage", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("uploadFile"); + } + }) + + + .add(Methods.DELETE, "/v2/store/order/{orderId}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("deleteOrder"); + } + }) + + + .add(Methods.GET, "/v2/store/inventory", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("getInventory"); + } + }) + + + .add(Methods.GET, "/v2/store/order/{orderId}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("getOrderById"); + } + }) + + + .add(Methods.POST, "/v2/store/order", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("placeOrder"); + } + }) + + + .add(Methods.POST, "/v2/user", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("createUser"); + } + }) + + + .add(Methods.POST, "/v2/user/createWithArray", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("createUsersWithArrayInput"); + } + }) + + + .add(Methods.POST, "/v2/user/createWithList", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("createUsersWithListInput"); + } + }) + + + .add(Methods.DELETE, "/v2/user/{username}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("deleteUser"); + } + }) + + + .add(Methods.GET, "/v2/user/{username}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("getUserByName"); + } + }) + + + .add(Methods.GET, "/v2/user/login", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("loginUser"); + } + }) + + + .add(Methods.GET, "/v2/user/logout", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("logoutUser"); + } + }) + + + .add(Methods.PUT, "/v2/user/{username}", new HttpHandler() { + public void handleRequest(HttpServerExchange exchange) throws Exception { + exchange.getResponseSender().send("updateUser"); + } + }) + + ; + return handler; + } +} + diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..2bdbadca1fe --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * A category for a pet + **/ + +@ApiModel(description = "A category for a pet") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.UndertowCodegen", date = "2016-09-26T16:15:27.984+08:00") +public class Category { + + private Long id = null; + private String name = null; + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/undertow/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..8c76fdef562 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,117 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Describes the result of uploading an image resource + **/ + +@ApiModel(description = "Describes the result of uploading an image resource") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.UndertowCodegen", date = "2016-09-26T16:15:27.984+08:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..8d309ccf898 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,200 @@ +package io.swagger.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.Date; + + + +/** + * An order for a pets from the pet store + **/ + +@ApiModel(description = "An order for a pets from the pet store") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.UndertowCodegen", date = "2016-09-26T16:15:27.984+08:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + + + public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } + + private StatusEnum status = null; + private Boolean complete = false; + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..da6af3805e6 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,203 @@ +package io.swagger.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.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + + + +/** + * A pet for sale in the pet store + **/ + +@ApiModel(description = "A pet for sale in the pet store") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.UndertowCodegen", date = "2016-09-26T16:15:27.984+08:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + + + public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } + + private StatusEnum status = null; + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..c404fabc9bf --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * A tag for a pet + **/ + +@ApiModel(description = "A tag for a pet") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.UndertowCodegen", date = "2016-09-26T16:15:27.984+08:00") +public class Tag { + + private Long id = null; + private String name = null; + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/undertow/src/main/java/io/swagger/model/User.java b/samples/server/petstore/undertow/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..bafd0663638 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/java/io/swagger/model/User.java @@ -0,0 +1,218 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * A User who is purchasing from the pet store + **/ + +@ApiModel(description = "A User who is purchasing from the pet store") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.UndertowCodegen", date = "2016-09-26T16:15:27.984+08:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(example = "null", value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/undertow/src/main/resources/META-INF/services/com.networknt.server.HandlerProvider b/samples/server/petstore/undertow/src/main/resources/META-INF/services/com.networknt.server.HandlerProvider new file mode 100644 index 00000000000..e6f7ef0b3e5 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/resources/META-INF/services/com.networknt.server.HandlerProvider @@ -0,0 +1 @@ +io.swagger.handler.PathHandlerProvider \ No newline at end of file diff --git a/samples/server/petstore/undertow/src/main/resources/config/oauth/primary.crt b/samples/server/petstore/undertow/src/main/resources/config/oauth/primary.crt new file mode 100644 index 00000000000..34f9272f81e --- /dev/null +++ b/samples/server/petstore/undertow/src/main/resources/config/oauth/primary.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDmzCCAoOgAwIBAgIEHnAgtDANBgkqhkiG9w0BAQsFADB+MQswCQYDVQQGEwJDQTEQMA4GA1UE +CBMHT250YXJpbzEUMBIGA1UEBxMLTWlzc2lzc2F1Z2ExJjAkBgNVBAoTHU5ldHdvcmsgTmV3IFRl +Y2hub2xvZ2llcyBJbmMuMQwwCgYDVQQLEwNERVYxETAPBgNVBAMTCFN0ZXZlIEh1MB4XDTE2MDkw +MTE2MTYxNVoXDTI2MDcxMTE2MTYxNVowfjELMAkGA1UEBhMCQ0ExEDAOBgNVBAgTB09udGFyaW8x +FDASBgNVBAcTC01pc3Npc3NhdWdhMSYwJAYDVQQKEx1OZXR3b3JrIE5ldyBUZWNobm9sb2dpZXMg +SW5jLjEMMAoGA1UECxMDREVWMREwDwYDVQQDEwhTdGV2ZSBIdTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBALrlxMtDb60DogElf4TBz504tRheZimAE0dJL/Yby4nacJdqvc5l4z+WWpDf +rI9krQ2Yi9yvhwAP+PrR6gWcIqWP4cpNE7XIAUDgr4CtyI7CptT/lpjtbkz4DGCMmaeDn0jqHqJt +SeSZGfwVu5zAGm8n4sHatjnnxBI/iWzkTII3V4xv0WeK37szNTEd+ly2ag7n2IV5zNnYmqZTeMQm +J2ENS+IwAG3ENtiVtrVTx/2bGtqutJjtdxsN58/cUG/guRyMT6OPI8Yi3ZzevdvRbxadyhEl/Kaw +6vJcdxmJI3tp4lx+p6sAxOWa7aapJe4JxutAQqzv0GKdVjoHKQ1wB60CAwEAAaMhMB8wHQYDVR0O +BBYEFIPF9SBd06RWU1eDL73CKfy01lavMA0GCSqGSIb3DQEBCwUAA4IBAQAoaKZGOak3Upz/ordF +slZoJuZlCu7jnKQEjYwHf3DNxcd1WmgFPtMcna6pW0VUxPIfidEA6VCMsGoK1RvshB0SjrRdCht6 +5qPXs9kV3NW0WvMiwDSYZZ9HgaZ9efTe5E9Fzc7ltKrE43L6k8NJcaEEWEdpdjFbrAqH4I+j/Vro +K3OhIo062fXjas5ipL4gF+3ECImjWzirQP8UiAfM0/36x7rtAu3btH/qI9hSyx39LBPPE5AsDJZ4 +dSMwNTW1gqmBAZIj+zQ/RD5dyWfPwON7Q+t96YbK6WBuYo0xy+I+PjcUgrWYWP3N24hlq8ZBIei+ +BudoEVJlIlmS0aRCuP8n +-----END CERTIFICATE----- diff --git a/samples/server/petstore/undertow/src/main/resources/config/security.json b/samples/server/petstore/undertow/src/main/resources/config/security.json new file mode 100644 index 00000000000..400070d0a2d --- /dev/null +++ b/samples/server/petstore/undertow/src/main/resources/config/security.json @@ -0,0 +1,13 @@ +{ + "description": "security configuration", + "enableVerifyJwt": false, + "jwt": { + "certificate": [ + "oauth/primary.crt" + ], + "clockSkewInSeconds": 60 + }, + "logJwtToken": true, + "logClientUserScope": false, + "enableVerifyScope": true +} \ No newline at end of file diff --git a/samples/server/petstore/undertow/src/main/resources/config/server.json b/samples/server/petstore/undertow/src/main/resources/config/server.json new file mode 100644 index 00000000000..14d16ce289a --- /dev/null +++ b/samples/server/petstore/undertow/src/main/resources/config/server.json @@ -0,0 +1,5 @@ +{ + "description": "server config", + "ip": "0.0.0.0", + "port": 8080 +} diff --git a/samples/server/petstore/undertow/src/main/resources/config/swagger.json b/samples/server/petstore/undertow/src/main/resources/config/swagger.json new file mode 100644 index 00000000000..a7b2b1871e6 --- /dev/null +++ b/samples/server/petstore/undertow/src/main/resources/config/swagger.json @@ -0,0 +1,871 @@ +{ + "swagger" : "2.0", + "info" : { + "description" : "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version" : "1.0.0", + "title" : "Swagger Petstore", + "termsOfService" : "http://swagger.io/terms/", + "contact" : { + "email" : "apiteam@swagger.io" + }, + "license" : { + "name" : "Apache 2.0", + "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host" : "petstore.swagger.io", + "basePath" : "/v2", + "tags" : [ { + "name" : "pet", + "description" : "Everything about your Pets", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "schemes" : [ "http" ], + "paths" : { + "/pet" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "Add a new pet to the store", + "description" : "", + "operationId" : "addPet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "put" : { + "tags" : [ "pet" ], + "summary" : "Update an existing pet", + "description" : "", + "operationId" : "updatePet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/pet/findByStatus" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Finds Pets by status", + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "status", + "in" : "query", + "description" : "Status values that need to be considered for filter", + "required" : true, + "type" : "array", + "items" : { + "type" : "string", + "default" : "available", + "enum" : [ "available", "pending", "sold" ] + }, + "collectionFormat" : "csv" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Pet" + } + } + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/pet/findByTags" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Finds Pets by tags", + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : true, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "csv" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Pet" + } + } + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/pet/{petId}" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Find pet by ID", + "description" : "Returns a single pet", + "operationId" : "getPetById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to return", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Pet" + } + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Updates a pet in the store with form data", + "description" : "", + "operationId" : "updatePetWithForm", + "consumes" : [ "application/x-www-form-urlencoded" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "name" : "name", + "in" : "formData", + "description" : "Updated name of the pet", + "required" : false, + "type" : "string" + }, { + "name" : "status", + "in" : "formData", + "description" : "Updated status of the pet", + "required" : false, + "type" : "string" + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/x-www-form-urlencoded", + "x-accepts" : "application/json" + }, + "delete" : { + "tags" : [ "pet" ], + "summary" : "Deletes a pet", + "description" : "", + "operationId" : "deletePet", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "api_key", + "in" : "header", + "required" : false, + "type" : "string" + }, { + "name" : "petId", + "in" : "path", + "description" : "Pet id to delete", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "uploads an image", + "description" : "", + "operationId" : "uploadFile", + "consumes" : [ "multipart/form-data" ], + "produces" : [ "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to update", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "name" : "additionalMetadata", + "in" : "formData", + "description" : "Additional data to pass to server", + "required" : false, + "type" : "string" + }, { + "name" : "file", + "in" : "formData", + "description" : "file to upload", + "required" : false, + "type" : "file" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/ApiResponse" + } + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "x-contentType" : "multipart/form-data", + "x-accepts" : "application/json" + } + }, + "/store/inventory" : { + "get" : { + "tags" : [ "store" ], + "summary" : "Returns pet inventories by status", + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "produces" : [ "application/json" ], + "parameters" : [ ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "object", + "additionalProperties" : { + "type" : "integer", + "format" : "int32" + } + } + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/store/order" : { + "post" : { + "tags" : [ "store" ], + "summary" : "Place an order for a pet", + "description" : "", + "operationId" : "placeOrder", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "order placed for purchasing the pet", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Order" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid Order" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/store/order/{orderId}" : { + "get" : { + "tags" : [ "store" ], + "summary" : "Find purchase order by ID", + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId" : "getOrderById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "integer", + "maximum" : 5.0, + "minimum" : 1.0, + "format" : "int64" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "delete" : { + "tags" : [ "store" ], + "summary" : "Delete purchase order by ID", + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "string", + "minimum" : 1.0 + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/user" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Create user", + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Created user object", + "required" : true, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/user/createWithArray" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "description" : "", + "operationId" : "createUsersWithArrayInput", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/User" + } + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/user/createWithList" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "description" : "", + "operationId" : "createUsersWithListInput", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/User" + } + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/user/login" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs user into the system", + "description" : "", + "operationId" : "loginUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : true, + "type" : "string" + }, { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "string" + }, + "headers" : { + "X-Rate-Limit" : { + "type" : "integer", + "format" : "int32", + "description" : "calls per hour allowed by the user" + }, + "X-Expires-After" : { + "type" : "string", + "format" : "date-time", + "description" : "date in UTC when toekn expires" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "description" : "", + "operationId" : "logoutUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "description" : "", + "operationId" : "getUserByName", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be fetched. Use user1 for testing. ", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/User" + } + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "put" : { + "tags" : [ "user" ], + "summary" : "Updated user", + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "name that need to be deleted", + "required" : true, + "type" : "string" + }, { + "in" : "body", + "name" : "body", + "description" : "Updated user object", + "required" : true, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + }, + "delete" : { + "tags" : [ "user" ], + "summary" : "Delete user", + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be deleted", + "required" : true, + "type" : "string" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + } + }, + "securityDefinitions" : { + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" + }, + "petstore_auth" : { + "type" : "oauth2", + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "flow" : "implicit", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + }, + "definitions" : { + "Order" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "petId" : { + "type" : "integer", + "format" : "int64" + }, + "quantity" : { + "type" : "integer", + "format" : "int32" + }, + "shipDate" : { + "type" : "string", + "format" : "date-time" + }, + "status" : { + "type" : "string", + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ] + }, + "complete" : { + "type" : "boolean", + "default" : false + } + }, + "title" : "Pet Order", + "description" : "An order for a pets from the pet store", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet catehgry", + "description" : "A category for a pet", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "type" : "integer", + "format" : "int32", + "description" : "User Status" + } + }, + "title" : "a User", + "description" : "A User who is purchasing from the pet store", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "description" : "A tag for a pet", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "type" : "object", + "required" : [ "name", "photoUrls" ], + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "category" : { + "$ref" : "#/definitions/Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/definitions/Tag" + } + }, + "status" : { + "type" : "string", + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "title" : "a Pet", + "description" : "A pet for sale in the pet store", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "description" : "Describes the result of uploading an image resource" + } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + } +} \ No newline at end of file diff --git a/samples/yaml/pet.yml b/samples/yaml/pet.yml index 2d0891d3032..4b3420c99c8 100644 --- a/samples/yaml/pet.yml +++ b/samples/yaml/pet.yml @@ -87,7 +87,7 @@ apis: operations: - method: GET summary: Finds Pets by status - notes: Multiple status values can be provided with comma seperated strings + notes: Multiple status values can be provided with comma separated strings type: array items: $ref: Pet @@ -114,7 +114,7 @@ apis: operations: - method: GET summary: Finds Pets by tags - notes: "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + notes: "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." type: array items: $ref: Pet diff --git a/shippable.yml b/shippable.yml new file mode 100644 index 00000000000..97ed4286983 --- /dev/null +++ b/shippable.yml @@ -0,0 +1,15 @@ +language: java + +jdk: +- openjdk7 +- openjdk8 + +build: + cache: true + cache_dir_list: + - $HOME/.m2 + ci: + # generate all petstore sampless (client, servers, doc) + - ./bin/run-all-petstore 2>&1 > run-all-petstore.log + post_ci: + - tail run-all-petstore.log